0

为了便于编辑,我将命令拆分为几行:

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;
}
4

1 回答 1

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;

}

这不是一个很好的方法——正如我所说,一个命令是否“成功”可能意味着不同的事情——但在低级别上,如果一个命令运行没有任何错误/异常,那么它就是成功的,你就是已经在检查。

于 2012-05-29T11:59:15.810 回答