更新查询无效 - 需要帮助

时间:2015-10-13 13:35:32

标签: c# database visual-studio ms-access

private void Update_Click(object sender, EventArgs e)
{
    string loca="Pakistan";

    OleDbConnection con = new   OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\Usman\\Desktop\\db.accdb");

    OleDbCommand com = new OleDbCommand("Update INVENTORY SET Location=? WHERE itemID='1' ", con);
    com.Parameters.Add("@loca", OleDbType.VarChar).Value = loca;

    con.Open();

    try
    {
        com.ExecuteNonQuery();
    }
    catch(Exception f)
    {
        MessageBox.Show(f.Message);
        //MessageBox.Show("Given Data is not Valid", "Cannot Add", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }

    con.Close();

    gridview();
}

在这里,我更改了代码,没有错误是

  

没有给出一个或多个必需参数的值

更新查询无效,请帮我解决。

1 个答案:

答案 0 :(得分:3)

在C#中,你需要添加一个实际的参数对象并给它一个值:

string loca="Pakistan";
OleDbConnection con = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\Usman\\Desktop\\db.accdb");

OleDbCommand com = new OleDbCommand("Update INVENTORY SET Location= ? WHERE itemID='1'", con);
com.Parameters.Add("@loca", OleDbType.VarWChar).Value = loca ?? (object)DBNull.Value;

其他一些建议/习惯:

  • using块中包裹您的连接和命令,以便及时处理它们
  • 不要只是捕捉异常并显示模糊的消息。包括异常详细信息或将其记录在某处,以便您知道实际错误是什么。
相关问题