更有效地在Access数据库上运行多个更新查询
本文关键字:更新 查询 运行 有效地 Access 数据库 | 更新日期: 2023-09-27 18:13:02
我现在有多个这样的查询,涉及更新Access数据库中同一行的不同字段:
//Update database
string updatequery = "UPDATE [table] SET [Last10Attempts] = ? WHERE id = ?";
OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;" + @"Data Source=" + "database.accdb");
con.Open();
OleDbDataAdapter da = new OleDbDataAdapter(updatequery, con);
var accessUpdateCommand = new OleDbCommand(updatequery, con);
accessUpdateCommand.Parameters.AddWithValue("Last10Attempts", last10attempts);
accessUpdateCommand.Parameters.AddWithValue("ID", currentid + 1);
da.UpdateCommand = accessUpdateCommand;
da.UpdateCommand.ExecuteNonQuery();
//update last10attemptssum
updatequery = "UPDATE [table] SET [Last10AttemptsSum] = ? WHERE id = ?";
accessUpdateCommand = new OleDbCommand(updatequery, con);
accessUpdateCommand.Parameters.AddWithValue("Last10AttemptsSum", counter);
accessUpdateCommand.Parameters.AddWithValue("ID", currentid + 1);
da.UpdateCommand = accessUpdateCommand;
da.UpdateCommand.ExecuteNonQuery();
//increment totalquestionattempt
updatequery = "UPDATE [table] SET [total-question-attempts] = ? WHERE id = ?";
accessUpdateCommand = new OleDbCommand(updatequery, con);
accessUpdateCommand.Parameters.AddWithValue("total-question-attempts", questionattempts + 1);
accessUpdateCommand.Parameters.AddWithValue("ID", currentid + 1);
da.UpdateCommand = accessUpdateCommand;
da.UpdateCommand.ExecuteNonQuery();
con.Close();
我想知道是否有一种更有效的方式来运行这些更新查询-即。将它们组合成一个查询
不需要在上面的上下文中使用OleDbDataAdapter。您可以使用一个简单的命令并执行它
就是说,Update sql语句可以更新多个字段。只写
string updatequery = @"UPDATE [table] SET [Last10Attempts] = ?,
[Last10AttemptsSum] = ?,
[total-question-attempts] = ?
WHERE id = ?";
using(OleDbConnection con = new OleDbConnection(.........))
using(OleDbCommand cmd = new OleDbCommand(updatequery, con))
{
con.Open();
cmd.Parameters.AddWithValue("Last10Attempts", last10attempts);
cmd.Parameters.AddWithValue("Last10AttemptsSum", counter);
cmd.Parameters.AddWithValue("total-question-attempts", questionattempts + 1);
cmd.Parameters.AddWithValue("ID", currentid + 1);
cmd.ExecuteNonQuery();
}
在使用OleDb时,唯一要保留的是参数的使用顺序与命令文本中参数占位符出现的顺序完全一致。因此,它们应该按照命令文本