【问题标题】:My records are not updating (only 1st row of DataGridView)我的记录没有更新(只有 DataGridView 的第一行)
【发布时间】:2014-09-18 15:10:26
【问题描述】:
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 数据库时,我看到只有第一条记录更新。其他的都没有动过。

我不确定自己做错了什么。

【问题讨论】:

  • 像这样一遍又一遍地打开和关闭连接是很奇怪的。为什么不在 foreach 循环的整个生命周期内保持打开状态(或者更好地在调用函数之前打开它并在完成后关闭它)。此外,尽管您正在关闭连接,但您并没有处理您的对象。你真的应该使用using 语句。
  • 你也永远不会使用你传递给函数的命令,你要做的第一件事就是把它扔掉并用myCommand = new OleDbCommand(SQL, Conn);覆盖它
  • 我认为这不会有太大作用。我在那里添加它以帮助我调试。
  • @ScottChamberlain 您能否在下面的答案部分中发布解决方案。使用是什么意思?
  • 我想我记得一个访问问题,不尊重参数的名称,只查看它们声明的顺序。如果您交换两个 AddWithValue 的顺序,它会起作用吗?

标签: c# ms-access oledb


【解决方案1】:

参数和访问存在一个已知问题。它不查看参数的名称,而是查看它们在查询中声明和使用的顺序。如果您切换两个 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();
          }
    }
}

【讨论】:

    猜你喜欢
    • 2014-12-13
    • 1970-01-01
    • 1970-01-01
    • 2012-07-29
    • 2020-12-16
    • 2022-01-19
    • 2010-10-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多