我想在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行\ n \ n \ n的'if exists'附近使用 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 力量)\ r \ n at MySql.Data.MySqlClient.MySqlDataReader.NextResult()\ r \ n at MySql.Data.MySqlClient.MySqlCommand.ExecuteReader(的CommandBehavior 行为)\ r \ n at MySql.Data.MySqlClient.MySqlCommand.ExecuteReader()\ r \ n at MySql.Data.MySqlClient.MySqlCommand.ExecuteNonQuery()\ r \ n at CSharpMySqlSample.Example2.Main()
那么查询有什么问题?
答案 0 :(得分:6)
试试这个:
DROP TABLE IF EXISTS sakila.testtable;
答案 1 :(得分:2)
请改为尝试:
String cmdText = @"IF OBJECT_ID('sakila'.'testable', 'U') IS NOT NULL DROP TABLE 'sakila'.'testable'";
还要确保运行程序的数据库用户具有删除表的必要权限,但是当您尝试运行此表时,您会立即看到: - )
答案 2 :(得分:2)
if exists
需要在表名前面。阅读docs ....
String cmdText = @"drop table if exists 'sakila'.'testable'";
答案 3 :(得分:1)
只需输入:
String cmdText = @"drop table `sakila`.`testable`";
没有“如果存在”
并且不要在 catch 中添加任何内容,因此您将删除表或不删除表取决于它是否存在而没有任何错误:)