2016-03-03 33 views
0

我试图根据在TextBox1的。我是在下面的代码得到错误给出的名称创建一个表表时:正确语法创建自TextBox名

附近有语法错误拉梅什“。

这里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 

回答

1

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

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 
3

您的表名不需要单引号。

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

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

另外我会说,使用参数化查询,但因为你不能参数化列名称,并且看起来像你得到它作为输入,使用强大的验证或使用白名单,然后再将其放入您的查询。

你可以阅读:The BobbyTables culture

+0

谢谢。是的,我尝试过使用这个,错误消失了,但表格并未在数据库中创建。 –

0

错误的直接原因是,你不应该把表名成撇号。这样的事情:

// put IDisposable into using 
using (SqlCommand cmd7 = new SqlCommand(
    // Keep SQL readable; "$" - C# 6.0 feature 
    [email protected]"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 
}