2

I am using:

        if (connection.State != ConnectionState.Open)
        {
            OpenConnection();
        }

and

private bool OpenConnection()
{
    try
    {
        connection.Open();
        return true;
    }
    catch (MySqlException ex)
    {
        //When handling errors, you can your application's response based 
        //on the error number.
        //The two most common error numbers when connecting are as follows:
        //0: Cannot connect to server.
        //1045: Invalid user name and/or password.
        switch (ex.Number)
        {
            case 0:
                Console.WriteLine("Cannot connect to server.  Contact administrator");
                Console.Read();
                break;

            case 1045:
                Console.WriteLine("Invalid username/password, please try again");
                Console.Read();
                break;
        }
        return false;
    }
}

I always get System.InvalidOperationException: The connection is already open. it doesn't make sense because I check if it's open already.

Thanks in advance.

1 Answer 1

2

There are connection states other than open and closed: Broken, Closed, Connecting, Executing, Fetching. You should only try to open if it's "Closed". If anything else it needs to be handled differently.

Sign up to request clarification or add additional context in comments.

1 Comment

@user1335122 print the connection state before if statement. That may give you some info regarding the state.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.