【问题标题】:Drop a table if it exists in C#?如果 C# 中存在表,则删除它?
【发布时间】:2013-11-08 07:04:41
【问题描述】:

我只想删除一个表,如果它存在,在 C# 和 MySql 中。

考虑以下代码:

namespace CSharpMySqlSample
{
   class Example2
   {
      static void Main()
      {
         String str = @"server=localhost; database=sakila; uid=root;                password=root;";
         MySqlConnection con = null;
         try
         {
            con = new MySqlConnection(str);
            con.Open(); //open the connection        
            String cmdText = @"drop table `sakila`.`testable` if exists"; // this one drops a table 
            MySqlCommand cmd = new MySqlCommand(cmdText, con);
            cmd.Prepare();
            cmd.ExecuteNonQuery(); //execute the mysql command
         }
         catch (MySqlException err)
         {
            String outp = err.ToString();
            Console.WriteLine("Error: " + err.ToString());
         }
         finally
         {
            if (con != null)
            {
               con.Close(); //close the connection
            }
         } //remember to close the connection after accessing the database
      }
   }
}

它产生了:

"MySql.Data.MySqlClient.MySqlException: 你的 SQL 有错误 句法;检查与您的 MySQL 服务器版本相对应的手册 在第 1 行的“如果存在”附近使用正确的语法\r\n at MySql.Data.MySqlClient.MySqlStream.ReadPacket()\r\n 在 MySql.Data.MySqlClient.NativeDriver.GetResult(Int32& 影响行, Int64& 插入 ID)\r\n 在 MySql.Data.MySqlClient.Driver.GetResult(Int32 statementId, Int32& 受影响的行、Int64 和插入的Id)\r\n at MySql.Data.MySqlClient.Driver.NextResult(Int32 statementId, Boolean 力)\r\n 在 MySql.Data.MySqlClient.MySqlDataReader.NextResult()\r\n 在 MySql.Data.MySqlClient.MySqlCommand.ExecuteReader(CommandBehavior 行为)\r\n 在 MySql.Data.MySqlClient.MySqlCommand.ExecuteReader()\r\n 在 MySql.Data.MySqlClient.MySqlCommand.ExecuteNonQuery()\r\n 在 CSharpMySqlSample.Example2.Main()

那么查询有什么问题?

【问题讨论】:

    标签: c# mysql


    【解决方案1】:

    试试这个:

    DROP TABLE IF EXISTS sakila.testtable;
    

    【讨论】:

      【解决方案2】:

      试试这个:

      String cmdText = @"IF OBJECT_ID('sakila'.'testable', 'U') IS NOT NULL DROP TABLE 'sakila'.'testable'";
      

      还要确保运行您的程序的数据库用户具有删除表的必要权限,但是当您尝试运行此程序时,您会立即看到 :-)

      【讨论】:

      • 不知道MySQL有OBJECT_ID()函数
      • 该死的。出于某种原因,我认为他使用的是 T-SQL (MS-SQL Server)。我的错。
      【解决方案3】:

      if exists 需要放在表名之前。阅读docs....

      String cmdText = @"drop table if exists 'sakila'.'testable'"; 
      

      【讨论】:

        【解决方案4】:

        只需输入:

        String cmdText = @"drop table `sakila`.`testable`";
        

        没有“如果存在”

        并且不要在 catch 中添加任何内容,因此您是否会删除表取决于它是否存在而没有任何错误:)

        【讨论】:

          猜你喜欢
          • 2012-03-07
          • 1970-01-01
          • 1970-01-01
          • 2011-12-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-12-24
          相关资源
          最近更新 更多