我不确定我在这里做错了什么——在调试器中,对文件名所做的更改正确地应用于我为更新命令从中提取的数据集,但是当我检查之后数据库没有进行任何更改...所以我有点困惑...
using (System.Data.OleDb.OleDbConnection con = new System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=J:\\Physics.mdb"))
{
using (OleDbDataAdapter dbAdapter = new OleDbDataAdapter("select thesisID, filename FROM Theses", con))
{
DataSet ds = new DataSet();
con.Open();
dbAdapter.Fill(ds);
for (int j = 0; j < ds.Tables[0].Rows.Count; j++)
{
ds.Tables[0].Rows[j]["filename"] = ds.Tables[0].Rows[j]["filename"].ToString().Replace(',', '_');
string newFileName = ds.Tables[0].Rows[j]["filename"].ToString();
int ID = Convert.ToInt32(ds.Tables[0].Rows[j]["thesisID"].ToString());
using (OleDbCommand updateCommand = con.CreateCommand())
{
updateCommand.CommandText = "update theses set filename = @newFileName where thesisID = @ID";
updateCommand.Parameters.AddWithValue("@ID", ID);
updateCommand.Parameters.AddWithValue("@newFileName", newFileName);
updateCommand.ExecuteNonQuery();
}
}
con.Close();
}
}
请您参考如下方法:
尝试颠倒添加参数的顺序:
using (OleDbCommand updateCommand = con.CreateCommand())
{
updateCommand.CommandType = CommandType.Text;
updateCommand.CommandText = "update theses set filename = @newFileName where thesisID = @ID";
updateCommand.Parameters.AddWithValue("@newFileName", newFileName);
updateCommand.Parameters.AddWithValue("@ID", ID);
updateCommand.ExecuteNonQuery();
}
原因是OleDb doesn't support named parameters ,因此添加它们的顺序很重要。
请注意,OleDb 查询通常以这种方式表示:
using (OleDbCommand updateCommand = con.CreateCommand())
{
updateCommand.CommandType = CommandType.Text;
updateCommand.CommandText = "update theses set filename = ? where thesisID = ?";
updateCommand.Parameters.Add(new OleDbParameter("", "", ""...));
updateCommand.Parameters.Add(new OleDbParameter("", "", ""...));
updateCommand.ExecuteNonQuery();
}
这强调了顺序很重要 - 问号只是占位符,按照将参数添加到命令的顺序替换。
