简体   繁体   中英

Incorrect Syntax when creating table from textbox name

I was trying to create a table based on the name given in textbox1 .I am getting error in the following code :

Incorrect syntax near 'Ramesh'.

Here Ramesh was the value in textbox.

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

You don't need single quotes for your table name.

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

But weird part, don't use SqlCommand for MySQL. Use MySqlCommand and related class.

Also I would say that use parameterize queries but since you can't parameterize column name, and looks like you get it as an input, use strong validation or use whitelisting before you put it in your query.

You can read: The BobbyTables culture

remove ' from sides of the table name in query.

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

The immediate cause of the error is that you should not put table name into apostrophes. Something like this:

// 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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM