2

我在用

public static bool command(string input, MySqlConnection con)
{
    MySqlCommand command = new MySqlCommand(input, con);
    var resultSet = command.ExecuteNonQuery();

    if (!resultSet.Equals(0))
        return true;
    return false;
}

举个例子:

bool comm = mysql_command.command("INSERT INTO sometable (field1,field2) VALUES ('val1','val2')", connection);
if (!comm) textBox1.Text += "Command failed";
else textBox1.Text += "Command successful";

哪个正确添加Command successful到 textbox1。

但是当我更改sometable为时sometablee, textbox1 保持为空。我期待它通知我命令失败(sometablee不存在),但它没有。

谁能告诉我为什么?

完整代码:

mysql_命令:

class mysql_command
{
    public static bool command(string input, MySqlConnection con)
    {
        MySqlCommand command = new MySqlCommand(input, con);
        var resultSet = command.ExecuteNonQuery();

        if (!resultSet.Equals(0))
            return true;
        return false;
    }
}

mysql_connect:

class mysql_connect
{
    private MySqlConnection connection = null;

    public MySqlConnection connect(string server, string database, string UID, string password)
    {
        try
        {
            string MyConString = "SERVER=" + server + ";" +
                "DATABASE=" + database + ";" +
                "UID=" + UID + ";" +
                "PASSWORD=" + password + ";";
            connection = new MySqlConnection(MyConString);
            connection.Open();
        }
        catch (Exception ex) { Console.WriteLine("MySQL connect error : "+ex.Message); }
        return connection;
    }

    public void disconnect()
    {
        connection.Close();
    }
}

用法:

private void Form1_Load(object sender, EventArgs e)
{
    mysql_connect con = new mysql_connect();
    MySqlConnection connection = con.connect("server1.x.x", "somedb", "user", "pass");

    bool comm = mysql_command.command("INSERT INTO sometable (field1,field2) VALUES ('val1','val1')", connection);
    if (!comm) textBox1.Text += "Command failed";
    else textBox1.Text += "Command successful";
}
4

1 回答 1

1

原因如我所料,你的命令方法中会出现异常,

public static bool command(string input, MySqlConnection con)

因为请求的表不存在,....编辑您的命令方法以处理异常:

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;
    return false;
    }
    catch
    {}
    return false;
}
于 2012-04-30T18:41:27.983 回答