private void applyUpdates(OleDbCommand myCommand, OleDbConnection Conn)
foreach (DataGridViewRow row in dataGridView1.Rows)
{
String SQL = "Update UserList SET ActiveToday=@ActiveToday WHERE POID=@POID";
myCommand = new OleDbCommand(SQL, Conn);
myCommand.Parameters.AddWithValue("@POID", row.Cells["POID"].Value.ToString());
myCommand.Parameters.AddWithValue("@ActiveToday", 1);
Conn.Open();
myCommand.CommandType = CommandType.Text;
myCommand.ExecuteNonQuery();
Conn.Close();
}
}
以下内容将传递给上述方法
string connectionstring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Path\\database_be.accdb;Persist Security Info=False;";
OleDbConnection Conn = new OleDbConnection();
Conn.ConnectionString = connectionstring;
OleDbCommand myCommand = Conn.CreateCommand();
没有错误或崩溃。当我打开Access 2013数据库时,我看到只更新了第一条记录。其他的都没有动过。
我不确定我做错了什么。
答案 0 :(得分:2)
参数和Access存在已知问题。它不会查看参数的名称,而是查看它们在查询中声明和使用的顺序。如果您切换两个AddWithValue
来电的顺序,则应该修复它。
以下是使用“最佳做法”的代码的更新版本,使用using
语句来处理您的命令和连接,并重命名要遵循the naming guidelines的变量和方法。
private void SomeOtherMethod()
{
string connectionstring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Path\\database_be.accdb;Persist Security Info=False;";
using(var conn = new OleDbConnection(connectionstring))
{
conn.Open();
ApplyUpdates(conn);
} //The using statement closes the connection for you.
}
private void ApplyUpdates(OleDbConnection conn)
{
var sql = "Update UserList SET ActiveToday=@ActiveToday WHERE POID=@POID";
foreach (DataGridViewRow row in dataGridView1.Rows)
{
using(var myCommand = new OleDbCommand(sql, conn);
{
myCommand.CommandType = CommandType.Text; //I think it is text by default and this is unnessary
myCommand.Parameters.AddWithValue("@ActiveToday", 1);
myCommand.Parameters.AddWithValue("@POID", row.Cells["POID"].Value.ToString());
myCommand.ExecuteNonQuery();
}
}
}