Sql命令语法错误:System.Data.SqlClient.SqlException:'','''附近的语法不正确。

时间:2017-07-21 21:05:03

标签: c# syntax-error sqlcommand

我正在C#中构建销售点系统,我将数据从接口通过对象传递到数据库。

每次尝试更新时,更新函数都会在cmd.CommandText中抛出语法错误。

private void btnUpdate_Click(object sender, EventArgs e) //UPDATE FUNCTION//
    {
            user_management_system user_mgnt = new user_management_system();
            user_mgnt.Username = txt_userName.Text;
            user_mgnt.Password = txt_password.Text;
            user_mgnt.First_name = txt_firstName.Text;
            user_mgnt.Last_name = txt_lastName.Text;
            user_mgnt.Nationality = txt_nationality.Text;
            user_mgnt.Email = txt_email.Text;
            user_mgnt.Age = (txt_age.Text);
            con.Open();
            SqlCommand cmd = con.CreateCommand();
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "UPDATE userlogin SET password = ('"+ user_mgnt.Password + "',first_name='" + user_mgnt.First_name + "',last_name='" + user_mgnt.Last_name + "',age='" + user_mgnt.Age +
                          "',nationality='" + user_mgnt.Nationality + "',email='" + user_mgnt.Email + "', WHERE username ='"+ user_mgnt.Username+ "')";
           cmd.ExecuteNonQuery();
            con.Close();
            MessageBox.Show("Data has been successfuly updated");
            displaydata();

2 个答案:

答案 0 :(得分:2)

WHERE子句之前,您有一个额外的(放错位置的)逗号。它应该是:

cmd.CommandText = "UPDATE userlogin SET password = ('"+ user_mgnt.Password + "',first_name='" + user_mgnt.First_name + "',last_name='" + user_mgnt.Last_name + "',age='" + user_mgnt.Age +
                          "',nationality='" + user_mgnt.Nationality + "',email='" + user_mgnt.Email + "' WHERE username ='"+ user_mgnt.Username+ "')";

编辑:我同意那些评论你应该使用参数化SQL,并且还避免在数据库中存储纯文本密码。

答案 1 :(得分:-1)

查询文字中存在语法错误,请按照此表单

https://www.w3schools.com/sql/sql_update.asp