natli
natli

Reputation: 3822

Verify if mysql command executed

I am using

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

With as an example:

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";

Which correctly adds Command successful to textbox1.

But when I change sometable to sometablee, textbox1 stays empty. I was expecting it to notify me the command failed (sometablee does not exist), but it didn't.

Can anyone tell me why?

Full code:

mysql_command:

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();
    }
}

Usage:

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

Upvotes: 2

Views: 1736

Answers (1)

Saeed Amiri
Saeed Amiri

Reputation: 22555

The reason is as I expected, you will get an exception in your command method,

public static bool command(string input, MySqlConnection con)

because requested table is not exists, .... Edit your command method to handle exception:

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

Upvotes: 1

Related Questions