不要使用ID更新MS Access数据库

时间:2018-12-29 12:36:49

标签: c# database ms-access sql-update

我尝试编写一个程序来更新带有ID的数据。当我为id输入数字(例如id = 7)时,程序将运行并正常运行。但是,当我编写标签文本并转换为数字时,代码不会更新,并会引发错误。

这是我的代码:

private void yadda_saxla_update_Click(object sender, EventArgs e)
{
    connect.Open();  
    OleDbCommand cmd = new OleDbCommand();
    cmd.CommandText = "Update Guller set gulun_adi='"+gul_adi.Text+ "', sekil='" + gulun_adi_label.Text + "' where id='"+Convert.ToInt32( id_label.Text)+"'";

    // when i write "id=7" or other number data is update, 
    // but i want update with label text (  Convert.ToInt32( id_label.Text)  )
    // and gives error

    cmd.Connection = connect;
    cmd.ExecuteNonQuery();
    connect.Close();
    disp_data();
}

错误如下:

error

我该怎么办?谢谢...

1 个答案:

答案 0 :(得分:0)

正如其他人在评论中指出的那样,您不应不要连接用户输入,因为它为SQL Injection提供了攻击载体。 (或至少检查有害输入)

否则,我认为解决方法是您应该删除',因为目前该命令当前已解析为varchar。 where id='"+Convert.ToInt32( id_label.Text)+"'"这部分变成where id='7'而不是where id=7

因此,除非您的ID存储为varchar,否则应更改此行

cmd.CommandText = "Update Guller set gulun_adi='"+gul_adi.Text+ "', sekil='" + gulun_adi_label.Text + "' where id='"+Convert.ToInt32( id_label.Text)+"'";

cmd.CommandText = "Update Guller set gulun_adi='"+gul_adi.Text+ "', sekil='" + gulun_adi_label.Text + "' where id="+Convert.ToInt32( id_label.Text);