SQLCommand,创建表

时间:2018-04-18 09:05:42

标签: c# sql sqlcommand

我想在点击按钮后在我的数据库中创建表。在Button_Click函数中,我有一个代码

SqlConnection conn = new SqlConnection(@"MyConnectionString");

conn.Open();

SqlCommand cmd = new SqlCommand("CREATE TABLE '" + tableName+ "' (IdPy INT IDENTITY(1,1), Question NVARCHAR (MAX) NOT NULL, IsChecked BIT NOT NULL,  CONSTRAINTPK_'" + tableName+ "' PRIMARY KEY(Id) )", conn);

cmd.ExecuteNonQuery();
conn.Close();

tableName是我的String变量(其值2018-04-18 asd - 是的,我希望该表具有这样的名称)。单击按钮后出现错误:

  

System.Data.SqlClient.SqlException:' 2018-04-18 asd'附近的语法不正确。'

我认为问题出在我的SqlCommand中。如果你能帮助我解决这个问题,我将不胜感激。

3 个答案:

答案 0 :(得分:2)

tableName变量似乎是2018-04-18 asd。如果这确实是正确的表名,则需要将其(和约束)转义为方括号:

SqlCommand cmd = new SqlCommand("CREATE TABLE [" + tableName + "] (IdPy INT IDENTITY(1,1), Question NVARCHAR (MAX) NOT NULL, IsChecked BIT NOT NULL, CONSTRAINT [CONSTRAINTPK_" + tableName+ "] PRIMARY KEY(Id) )", conn);

答案 1 :(得分:2)

您应该转义(如果是MS SQL,则为[...] table 约束名称:

  //DONE: wrap IDisposable into using
  using(SqlConnection conn = new SqlConnection(@"MyConnectionString")) {
    conn.Open();

    //DONE: Make sql readable. Can you see that you've skipped CONSTRAINT keyword?
    string sql = 
      $@"CREATE TABLE [{tableName}] (
           -- Fields
           IdPy      INT IDENTITY(1,1),
           Question  NVARCHAR (MAX)     NOT NULL, 
           IsChecked BIT                NOT NULL,

           -- Constraints
           --DONE: Constraint key word (optional in some RDBMS) added 
           CONSTRAINT [CONSTRAINTPK_{tableName}] PRIMARY KEY(Id) 
         )";

    //DONE: wrap IDisposable into using
    using (qlCommand cmd = new SqlCommand(sql, conn)) {
      cmd.ExecuteNonQuery();
    }
  } 

答案 2 :(得分:0)

通过使用字符串变量和参数化字符串格式来识别SQLCommand的问题可能更容易。一个例子:

string query = "CREATE TABLE @tablename (IdPy INT IDENTITY(1,1), 
Question NVARCHAR (MAX) NOT NULL, IsChecked BIT NOT NULL,  
CONSTRAINTPK_@tablename PRIMARY KEY(Id) )";

string param = new {@tablename = txttable.txt(example)};

SqlCommand cmd = new SqlCommand(query, param, conn);

这可能有助于逐步确保您需要检查的变量更简洁。