我的c#更新代码出了什么问题?

时间:2014-04-28 07:17:33

标签: c#

我编写了具有id,年份和状态的代码。状态是一个梳子盒,它有4个项目,当我尝试运行这个代码时,它一直告诉我由于UPDATE语句中的Syntax错误而失败,你能给我一些想法吗?

private void button3_Click(object sender, EventArgs e)
{
    try
    {
        conn.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;" +
            @"Data source= C:\crt_db.accdb";

        conn.Open();
        String year = dateTimePicker1.Text.ToString();
        String status = comboBox2.Text.ToString();
        String z =EPID.Text.ToString();

        String my_querry = "update crtRenewald set Year='" + year + "',Status='" + status+ "' where EPID=" + z + "";                
        OleDbCommand cmd1 = new OleDbCommand(my_querry, conn);
        cmd1.ExecuteNonQuery();

        MessageBox.Show("Status updated");
    }
    catch (Exception ex)
    {
        MessageBox.Show("Failed due to" + ex.Message);
    }
    finally
    {
        conn.Close();
    }

2 个答案:

答案 0 :(得分:2)

我认为UPDATE查询字符串中的引号不正确。尝试将其更改为:

String my_querry = "update crtRenewald set Year='" + year + "',Status='" + status + "' where EPID='" + z + "'";

答案 1 :(得分:1)

试试这段代码,对您有所帮助: -

我根据你的sql syntex使用参数化查询。

     conn.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;" +@"Data source= C:\crt_db.accdb";

     conn.Open();

    using (OleDbCommand cmd = conn.CreateCommand())
    {
        OleDbCommand scmd = new OleDbCommand("UPDATE crtRenewald SET Year=@Year, Status=@Status where @EPID=EPID", conn);
        scmd.Parameters.AddWithValue("Year", dateTimePicker1.Text.ToString());
        scmd.Parameters.AddWithValue("Status", comboBox2.Text.ToString());
        scmd.Parameters.AddWithValue("EPID", EPID.Text.ToString());

        scmd.ExecuteNonQuery();
     }

     conn.Close();