2016-02-22 46 views
-2

我'得到以下錯誤:我不能在c#中解決這個錯誤?

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near "temp" at line 1.

下面的代碼:

public void DeleteColumn(string columnName) 
{ 
    try 
    { 
     query.CommandText = "alter table publisher drop @col "; 
     query.Prepare(); 
     query.Parameters.AddWithValue("@col", columnName); 
     query.ExecuteNonQuery(); 
     Console.WriteLine("column deleted successfully"); 
     transaction.Commit(); 
     Console.WriteLine("successfully committed to database"); 
    } 
    catch (MySqlException ex) 
    { 
     Console.WriteLine(ex.Message); 
    } 
} 

我這是在傳遞DeleteColumn值:

DeleteColumn("temp"); 

沒有連接問題,我已經定義了每個需要的值

+0

你有沒有調試代碼,如果是,請告訴我哪行代碼拋出異常 – Pawan

+0

是的。 query.ExecuteNonQuery();拋出異常 – Ankit0047

+0

query.CommandText =「alter table publisher DROP COLUMN @col」;將解決。改變這一行 – Pawan

回答

0

你需要一個column添加到您的drop語句

query.CommandText = "alter table publisher drop column @col "; 
0

爲什麼你期望你的代碼是不工作:

您在給定的查詢按照mysql語法有錯誤;正確的語法使用alter table如下:刪除列:

ALTER TABLE "table_name" 
DROP "column_name"; 

解決方案

更改您的CommandText如下所示:

query.CommandText = "alter table publisher DROP COLUMN @col "; 

和參數將是這樣的:

query.Parameters.AddWithValue("@col", columnName);//passed value to the function this must be the column name. 

因此,你的tr y塊將是:

try 
    { 
     query.CommandText = "alter table publisher DROP COLUMN @col ";  
     query.Parameters.AddWithValue("@col", columnName); 
     int result=query.ExecuteNonQuery(); 
     transaction.Commit(); 
     if(result>0) 
     Console.WriteLine("column deleted successfully"); 
     else 
     Console.WriteLine("successfully committed to database"); 
    } 
+0

仍然不工作? – Ankit0047

+1

不工作意味着什麼?你有什麼錯誤嗎? –

+0

是的,我收到相同的錯誤 – Ankit0047

0

SQL查詢語法是錯誤的,使用這個。

query.CommandText = "alter table publisher DROP COLUMN @col ";