我无法在c#中解决此错误?

时间:2016-02-22 05:29:53

标签: c# mysql

我收到以下错误:

  

您的SQL语法中有错误;检查手册   对应于您的MySQL服务器版本,以使用正确的语法   在第1行“ temp ”附近。

以下是代码:

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");

连接没有问题,我已经定义了所有需要的值

3 个答案:

答案 0 :(得分:0)

您需要在drop语句中添加column

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

答案 1 :(得分: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.

因此你的尝试块将是:

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");
    }

答案 2 :(得分:0)

Sql查询语法错误,请使用此。

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