我需要用MS-Access中的链接打开一些文件夹。我的代码如下,但不起作用:
DataSet DSOne = new DataSet();
OleDbDataAdapter adp = new OleDbDataAdapter();
private void button2_Click(object sender, EventArgs e)
{
adp.SelectCommand = new OleDbCommand();
adp.SelectCommand.Connection = oleDbConnection1;
adp.SelectCommand.CommandText = " select Folder from Sheet where ID like '%" + textBox9.Text + "%' or OfficialDossier like '%" + textBox9.Text + "%' or Family like '%" + textBox9.Text + "%' or FirstName like '%" + textBox9.Text + "%' or approve like '%" + textBox9.Text + "%' or City like '%" + textBox9.Text + "%' or Department like '%" + textBox9.Text + "%' or Organization like '%" + textBox9.Text + "%' ";
adp.SelectCommand.Parameters.AddWithValue("@ID", textBox9.Text);
adp.Fill(DSOne, "Folder");
string p = "Folder";
string args = string.Format("/e, /select, \"{0}\"", p);
ProcessStartInfo info = new ProcessStartInfo();
info.FileName = "explorer";
info.Arguments = args;
Process.Start(info);
}
此代码分为两部分:一部分直到adp.Fill(SDOne, "Folder");
并且它正常工作!我得到DataGridView
datasource
和datamember
的结果。
string p = "Folder";
的第二部分也起作用了!当我获取字符串地址时,此代码打开它。
我认为问题是在adp.Fill (DSOne, "Folder");
和String之间转换,我不知道如何将datamember
放到字符串中。
谢谢你的帮助!
答案 0 :(得分:0)
您似乎执行命令从数据库中检索文件夹(稍后会详细介绍)但您忘记读取该值并使用它来打开文件系统文件夹
adp.Fill(DSOne, "Folder");
if(DSOne.Tables[0].Rows.Count > 0)
{
// Here you are sure that the first table of the dataset contains at least one record.
// So you could retrieve it (Rows[0]) and then access the first column
// of that row (Rows[0]["Folder"])
string p = DSOne.Tables[0].Rows[0]["Folder"].ToString();
string args = string.Format("/e, /select, \"{0}\"", p);
ProcessStartInfo info = new ProcessStartInfo();
info.FileName = "explorer";
info.Arguments = args;
Process.Start(info);
}
构建sql命令的任何类型的字符串连接都注定要失败。您不应该使用该方法,但始终使用参数化查询。在上面的代码中,似乎您添加了一个参数,并且从不使用此参数。我建议将代码的这一部分改为
adp.SelectCommand = new OleDbCommand();
adp.SelectCommand.Connection = oleDbConnection1;
adp.SelectCommand.CommandText = @"SELECT Folder FROM Sheet
WHERE ID LIKE ? or OfficialDossier LIKE ? or Family LIKE ? or
FirstName LIKE ? or approve LIKE ? or City LIKE ? or
Department LIKE ? or Organization LIKE ?";
string parameterValue = "%" + textBox9.Text + "%";
adp.SelectCommand.Parameters.AddWithValue("@p1", parameterValue);
adp.SelectCommand.Parameters.AddWithValue("@p2", parameterValue);
adp.SelectCommand.Parameters.AddWithValue("@p3", parameterValue);
adp.SelectCommand.Parameters.AddWithValue("@p4", parameterValue);
adp.SelectCommand.Parameters.AddWithValue("@p5", parameterValue);
adp.SelectCommand.Parameters.AddWithValue("@p6", parameterValue);
adp.SelectCommand.Parameters.AddWithValue("@p7", parameterValue);
adp.SelectCommand.Parameters.AddWithValue("@p8", parameterValue);
OleDb需要添加到命令集合中的确切参数数量,因为查询中存在多个占位符且顺序相同。在您的情况下,您始终使用由文本框提取的相同值并与sql通配符连接。因此,添加8个具有相同值的参数似乎是正确的。