c# - 如果表存在于 C# 中,则删除该表?

标签 c# mysql

我只想在 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: 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 'if exists' at line 1\r\n at MySql.Data.MySqlClient.MySqlStream.ReadPacket()\r\n at MySql.Data.MySqlClient.NativeDriver.GetResult(Int32& affectedRow, Int64& insertedId)\r\n at MySql.Data.MySqlClient.Driver.GetResult(Int32 statementId, Int32& affectedRows, Int64& insertedId)\r\n at MySql.Data.MySqlClient.Driver.NextResult(Int32 statementId, Boolean force)\r\n at MySql.Data.MySqlClient.MySqlDataReader.NextResult()\r\n at MySql.Data.MySqlClient.MySqlCommand.ExecuteReader(CommandBehavior behavior)\r\n at MySql.Data.MySqlClient.MySqlCommand.ExecuteReader()\r\n at MySql.Data.MySqlClient.MySqlCommand.ExecuteNonQuery()\r\n at CSharpMySqlSample.Example2.Main()

那么查询有什么问题呢?

最佳答案

试试这个:

DROP TABLE IF EXISTS sakila.testtable;

关于c# - 如果表存在于 C# 中,则删除该表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19848335/

相关文章:

php - 设计一个数据库来跟踪所有者

c# - Entity Framework 代码优先 CTP4 默认列值?

mysql密码错误并关闭

php - 反向 LIKE 函数查找搜索词的子字符串

php - 奇怪的 Mysql ORDER BY

mysql - 确定如何检索结果集数据(node.js + sequelize + 外键mysql)

c# - 是否有等同于 C++ std::partial_sort 的 C#?

c# - 如何根据百分比管理 AI 操作

c# - EPPlus 设置整个工作表的背景颜色

c# - Entity Framework "An object with the same key already exists in the ObjectStateManager."- 我无法理解如何从这里开始做什么