c# - Sql 命令语法错误 : System. Data.SqlClient.SqlException: 'Incorrect syntax near ' ,'.'

标签 c# syntax-error sqlcommand

我正在用 C# 构建一个销售点系统,并将数据从接口(interface)通过一个对象传递到数据库。

每次我尝试更新时,更新函数都会在 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();

最佳答案

您的 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,并且避免在数据库中存储纯文本密码。

关于c# - Sql 命令语法错误 : System. Data.SqlClient.SqlException: 'Incorrect syntax near ' ,'.',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45246688/

相关文章:

c# - 无法开始调试。启动项目无法启动

c++ - 错误代码Visual Studio错误:c2059 strange syntax error

python - sqlite3.操作错误: near "?": syntax error in python -- using 'IN' operator

r - As 公式中的意外符号,无法找到

c# - SqlCommand 在另一个函数中使用时什么时候关闭?

c# - 如何使用更新语句(C# sqlcommand)将 NCHAR 设置为空

c# - 使用字节复制文件+进度条

c# - 500 自定义错误从不显示但在预览中

mysql - "On Delete Cascade"如果从子表中删除一行

c# - 事件没有被解雇