我不确定我在这里做错了什么 - 在调试器中对文件名所做的更改是正确的,我正在为我的更新命令提取数据集,但当我检查时数据库之后没有做出任何改变......所以我有点困惑......
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();
}
}
答案 0 :(得分:4)
尝试颠倒添加参数的顺序:
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();
}
这强调订单很重要 - 问号只是占位符,它们会按参数添加到命令的顺序替换。