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

时间:2013-06-02 05:48:45

标签: c# ms-access ms-access-2007

我有一个数据网格,我应该将其列值插入访问数据库,但我遇到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();

2 个答案:

答案 0 :(得分:1)

正如上面其中一条评论中所建议的那样,您应该首先更改代码以使用参数化查询。这将减轻您划分值的需要,并且还可以使您的代码更安全。此外,您应该利用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语句中的字段名称。

答案 1 :(得分:0)

这意味着在表中找不到列,(因此Access认为它是一个参数)。通常你拼错了一些东西。似乎“restOfMonyy”应该是“restOfMoney”。如果没有,请调试应用程序并获取构建的确切字符串并使用它进行查询,看看会发生什么。