数据库错误:“没有为一个或多个必需参数给出值。”

2023-12-09

我有一个数据网格,我应该将其列值插入到访问数据库中,但我有问题command.ExecuteNonQuery();

我的项目因为这个错误而没有完成。这是我的代码:

for (int i = 0; i < (dataGridFactorRent.Rows.Count) - 1; i++)
{
    string query =
        @"INSERT INTO tbl_RentFactor([ID],DateNow,customerName, objectName, 
          objectNumber,unitCost,objectCost,paidMoney,restOfMonyy,customerID,DateBack)
          VALUES ("+ID+",'" + lbldate.Text + "','" + cmdCustomName.Text + "'," +
              dataGridFactorRent.Rows[i].Cells[1].Value + ",
              " + dataGridFactorRent.Rows[i].Cells[3].Value + ",
              " + dataGridFactorRent.Rows[i].Cells[4].Value + ",
              " + dataGridFactorRent.Rows[i].Cells[5].Value + ",
              '" + txtPaid.Text + "','" + lblRemained.Text + "',
              "+customerID+",'"+lbldate.Text+"')";

    con.Open();
    command.CommandText =query;
    command.ExecuteNonQuery();
    con.Close();

正如上面评论之一所建议的,您应该首先更改代码以使用参数化查询。这将使您不再需要分隔值,并且还会使您的代码更安全。此外,您应该利用using声明让.NET更好地管理资源。

进行这些更改后,您的代码将看起来更像这样:

string query =
    @"INSERT INTO tbl_RentFactor([ID],DateNow,customerName, objectName, 
      objectNumber,unitCost,objectCost,paidMoney,restOfMonyy,customerID,DateBack)
      VALUES (?,?,?,?,?,?,?,?,?,?,?)";
con.Open();
for (int i = 0; i < (dataGridFactorRent.Rows.Count) - 1; i++)
{
    using (var command = new OleDbCommand(query, con));
    {
        command.Parameters.AddWithValue("?", ID);
        command.Parameters.AddWithValue("?", lbldate.Text);
        command.Parameters.AddWithValue("?", cmdCustomName.Text);
        command.Parameters.AddWithValue("?", dataGridFactorRent.Rows[i].Cells[1].Value);
        command.Parameters.AddWithValue("?", dataGridFactorRent.Rows[i].Cells[3].Value);
        command.Parameters.AddWithValue("?", dataGridFactorRent.Rows[i].Cells[4].Value);
        command.Parameters.AddWithValue("?", dataGridFactorRent.Rows[i].Cells[5].Value);
        command.Parameters.AddWithValue("?", txtPaid.Text);
        command.Parameters.AddWithValue("?", lblRemained.Text);
        command.Parameters.AddWithValue("?", customerID);
        command.Parameters.AddWithValue("?", lbldate.Text);

        command.ExecuteNonQuery();
    }
}
con.Close();

如果进行这些修改后仍然收到错误,请仔细检查 INSERT 语句中的字段名称。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

数据库错误:“没有为一个或多个必需参数给出值。” 的相关文章

随机推荐