如果C#中存在表,则删除该表吗? [英] Drop a table if it exists in C#?
问题描述
我只想使用MySql在C#中删除表(如果存在).
I want to drop a table only if it exists , in C# with 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处的如果存在"附近使用正确的语法 MySql.Data.MySqlClient.MySqlStream.ReadPacket()\ r \ n在 MySql.Data.MySqlClient.NativeDriver.GetResult(Int32& Row, Int64& insertId)\ r \ n位于 MySql.Data.MySqlClient.Driver.GetResult(Int32 statementId,Int32& 受影响的行,Int64& insertId)\ r \ n位于 MySql.Data.MySqlClient.Driver.NextResult(Int32 statementId,Boolean 力)\ r \ n at 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()
"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()
那么查询出了什么问题?
So what's wrong with the query ?
推荐答案
尝试一下:
DROP TABLE IF EXISTS sakila.testtable;
这篇关于如果C#中存在表,则删除该表吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!