【问题标题】:'System.Data.SqlClient.SqlException' in System.Data.dll ("Incorrect syntax near ')'.")?System.Data.dll 中的“System.Data.SqlClient.SqlException”(“')' 附近的语法不正确。”)?
【发布时间】:2018-05-18 09:02:56
【问题描述】:

嘿,这是我的代码,这是我得到的错误:

抛出异常:“System.Data.SqlClient.SqlException”在 System.Data.dll ("')' 附近的语法不正确。")


void addMember() 
{
    try 
    {
       //con.Open();
        String EmpID = txtEmpID.Text.ToString().Trim();
        String EmployeeName = txtEmpID.Text.ToString().Trim();
        String UserName = txtUsername.Text.ToString().Trim();
        String UserType = cmbUserType.GetItemText(cmbUserType.SelectedItem);
        String PassWord = txtPassword.Text.ToString().Trim();
        SqlCommand addUser = new SqlCommand("insert into  userDetails(@empID ,@employeeName ,@userName , @userType, @password)", con);
        addUser.Parameters.Add(new SqlParameter("@empID", EmpID));
        addUser.Parameters.Add(new SqlParameter("@employeeName", EmployeeName));
        addUser.Parameters.Add(new SqlParameter("@userName", UserName));
        addUser.Parameters.Add(new SqlParameter("@userType", UserType));
        addUser.Parameters.Add(new SqlParameter("@password", PassWord));

        int x = addUser.ExecuteNonQuery();

        if (x > 0)
        {

            MessageBox.Show("Data Inserted", "User Form", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
        //con.Close();
    }
    catch (Exception ex) 
    {
        MessageBox.Show("" + ex);
    }

【问题讨论】:

  • 不要在未指定列名的情况下将插入写入查询。如果出于任何原因向该表添加新列,您的代码将中断。 (你会从一开始就避免这个错误)
  • 为什么有人在这里贴代码,却又慌张又拒绝学习使用调试器..? Google is a great free tool for learning SQL Syntax
  • 调试器在这里并不能真正帮助您……这是一个 sql 语法问题。但是,您是否有理由需要使用原始 SQL 命令和实体框架?

标签: c# sql sql-server exception ado.net


【解决方案1】:

您错过了Values 关键字:

SqlCommand addUser = new SqlCommand("insert into userDetails Values(@empID ," +
                                                              ^^^^
                                    "@employeeName ,@userName , @userType, @password)", con);

【讨论】:

  • 虽然正确,正如史蒂夫在上面指出的那样,但这只有在数据库中的列与您期望的确切顺序一致时才有效。这可能是一个合理的假设。但是,如果您使用 EF(以及确保您的数据库与 EDM 同步的工具),您可以更轻松地捕获/防止应用程序代码和数据库架构之间的不匹配。
  • 非常感谢你们不能相信我错过了
  • 感谢支持
猜你喜欢
  • 2021-03-31
  • 2019-07-17
  • 2017-12-08
  • 2014-05-09
  • 2018-05-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多