【问题标题】:Can't Enter SQL Command with C#无法使用 C# 输入 SQL 命令
【发布时间】:2015-01-12 06:19:51
【问题描述】:

我正在尝试让我的程序进入我的 SQL Server 数据库,但是当我运行它时,我收到一个错误,提示')'附近的语法不正确。

SqlConnection conn = new SqlConnection("Data Source=AJ-PC;Initial Catalog=Customers;Integrated Security=True");
conn.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO Customers ('1', '1', '1', '1000/01/01', '1', '1')", conn);
cmd.ExecuteNonQuery();
conn.Close();

【问题讨论】:

  • “寻求调试帮助的问题(“为什么这段代码不起作用?”)必须包含所需的行为”
  • 您最好学习使用参数的正确方法,例如参见以下答案:stackoverflow.com/a/19956944/1599751

标签: c# sql sql-server


【解决方案1】:

应该是:

SqlCommand cmd = new SqlCommand("INSERT INTO Customers(col1, col, col3, ....) VALUES ('1', '1', '1', '1000/01/01', '1', '1')", conn);
                                                                              ******

您需要指定 VALUES 关键字,并且我建议始终在要插入的表中指定明确的列列表。

【讨论】:

    【解决方案2】:

    您在查询中错过了VALUES 关键字

    INSERT INTO Customers VALUES ('1', '1', '1', '1000/01/01', '1', '1')
    

    【讨论】:

      【解决方案3】:

      这样做:

      SqlCommand cmd = new SqlCommand("INSERT INTO Customers (column names...) values('1', '1', '1', '1000/01/01', '1', '1')",con);
      

      您没有指定列名和 Values 关键字。

      【讨论】:

        【解决方案4】:

        我知道这以不同的方式回答了这个问题。但这是为了将来参考。我建议你使用try...catch...finally 块。

        SqlCommand cmd;
        try {
            conn.Open();
            string query = "INSERT INTO Customers (col1, col2, col3,...) VALUES ('val1', 'val2', 'val3',...)";
            cmd = new SqlCommand(query, conn);
            int RowsAffected = cmd.ExecuteNonQuery();
            if(RowsAffected > 0) {
            //If you are on Console:
            Console.WriteLine("1 Row Inserted");
        
            //If you are on WinForms / WebForms:
            lblMessage.Text = "1 Row Inserted";
        } catch (Exception ex) {
            //If you are on Console:
            Console.WriteLine("Some Exception: " + ex.Message.ToString());
        
            //If you are on WinForms / WebForms:
            lblMessage.Text = "Some Exception: " + ex.Message.ToString();
        } finally {
            conn.Close();
        }
        

        【讨论】:

        • 或者更好:将您的SqlConnectionSqlCommand 放入using (...) { ...... } 块中!
        【解决方案5】:

        您可能错过了在命令中包含“VALUES”子句。 你会像下面这样使用它

        插入 Table_Name(Col1,Col2,...ColN) VALUES (VAL1,VAL2,...VAL3)

        在哪里, Table_Name- 你的表名 Col1,Col2,...ColN- 表中的列名 VAL1,VAL2,...VAL3- 提供给各个列的值

        希望这对你有用

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-01-03
          • 1970-01-01
          • 1970-01-01
          • 2011-11-14
          • 2022-10-19
          • 1970-01-01
          • 1970-01-01
          • 2014-12-08
          相关资源
          最近更新 更多