从文本框名称创建表时语法不正确

本文关键字:语法 不正确 创建 文本 | 更新日期: 2023-09-27 18:37:06

我试图根据文本框 1 中给出的名称创建一个表。我在以下代码中收到错误:

"Ramesh"附近的语法不正确。

这里 Ramesh 是文本框中的值。

string Customername = Textbox1.text 
SqlCommand cmd7 = new SqlCommand("CREATE TABLE '" + CustomerName + "' (ItemCode int,Quantity int,PricePerQuantity int,Brand char(50),Discount int , DateTime datetime)",connection

从文本框名称创建表时语法不正确

表名不需要单引号。

SqlCommand cmd7 = new SqlCommand("CREATE TABLE " + CustomerName + " (ItemCode int,Quantity int,PricePerQuantity int,Brand char(50),Discount int , DateTime datetime)",connection);

但奇怪的部分,不要将SqlCommand用于MySQL。使用MySqlCommand和相关类。

另外,我会说使用参数化查询,但由于您无法参数化列名称,并且看起来您将其作为输入,因此在将其放入查询之前,请使用强验证或使用白名单。

您可以阅读: BobbyTables 文化

查询中从表名的两侧删除'

string Customername = Textbox1.text 
SqlCommand cmd7 = new SqlCommand("CREATE TABLE " + CustomerName + " (ItemCode int,Quantity int,PricePerQuantity int,Brand char(50),Discount int , DateTime datetime)",connection

错误的直接原因是您不应该将表名放入撇号中。像这样:

// put IDisposable into using
using (SqlCommand cmd7 = new SqlCommand(
  // Keep SQL readable; "$" - C# 6.0 feature
  $@"CREATE TABLE {Textbox1.text}(
       ItemCode int,
       Quantity int, 
       PricePerQuantity int,
       Brand char(50),
       Discount int, 
       DateTime datetime)", 
  connection)) {
  cmd7.ExecuteNonQuery(); // execute and create the table
}