2016-03-03 58 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 
}