我将命令分成几行以便于编辑:
string docommand = "";
docommand += "DROP TABLE IF EXISTS `config`;";
//docommand += "/*!40101 SET @saved_cs_client = @@character_set_client */;";
//docommand += "/*!40101 SET character_set_client = utf8 */;";
docommand += "CREATE TABLE `config` (";
docommand += " `name` varchar(200) NOT NULL,";
docommand += " `value` varchar(200) NOT NULL,";
docommand += " `timestamp` int(11) NOT NULL,";
docommand += " UNIQUE KEY `name` (`name`)";
docommand += ")";
//docommand += " ENGINE=MyISAM DEFAULT CHARSET=latin1";
docommand += ";";
//docommand += "/*!40101 SET character_set_client = @saved_cs_client */;";
mysql_connect connect = new mysql_connect();
MySqlConnection conn = connect.connect(core_config.server, core_config.database, core_config.username, core_config.pass);
bool success = mysql_command.command(docommand, conn);
connect.disconnect();
if (!success)
Console.WriteLine("Command failed : " + docommand);
正如你所看到的,我评论了几行,看看它们是否造成了麻烦。没有什么区别。
输出:
Returning false because resultSet is 0
Command failed : DROP TABLE IF EXISTS `config`;CREATE TABLE `config` ( `name` varchar(200) NOT NULL, `value` varchar(200) NOT NULL, `timestamp` int(11) NOT NULL, UNIQUE KEY `name` (`name`));
但表格已正确创建...当我在phpmyadmin
中粘贴完全相同的命令并从那里运行时,它会报告没有任何问题。
像"SELECT * FROM config"
这样的命令不报告失败。那么为什么CREATE TABLE命令呢?
mysql_command.command()功能:
public static bool command(string input, MySqlConnection con)
{
try
{
MySqlCommand command = new MySqlCommand(input, con);
var resultSet = command.ExecuteNonQuery();
if (!resultSet.Equals(0))
{
return true;
}
Console.WriteLine("Returning false because resultSet is 0");
return false;
}
catch (Exception ex) { Console.WriteLine("MySQL command error : "+ex.Message); }
Console.WriteLine("Returning false after exception");
return false;
}
答案 0 :(得分:1)
两者 DROP TABLE和CREATE TABLE不会发回0以外的任何内容。因此,您的“命令”方法始终认为该命令失败。 ExecuteNonQuery()将返回受您的语句影响的行,这将是0。
你能做什么,传递你期望它改变的行数,所以像这样:
public static bool command(string input, MySqlConnection con, int expectedRowsAffected = 0)
{
try
{
MySqlCommand command = new MySqlCommand(input, con);
var resultSet = command.ExecuteNonQuery();
if (resultSet.Equals(expectedRowsAffected))
{
return true;
}
Console.WriteLine(string.Format("Returning false because resultSet isn't {0}", expectedRowsAffected));
return false;
}
catch (Exception ex)
{
Console.WriteLine("MySQL command error : "+ex.Message);
}
Console.WriteLine("Returning false after exception");
return false;
}
这不是一个很好的方法 - 正如我所说,命令是否“成功”可能意味着不同的东西 - 但是在低级别,如果命令运行没有任何错误/异常,则命令成功,你已经在检查了。