2

我在用:

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

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

我总是得到System.InvalidOperationException: The connection is already open。这没有意义,因为我检查它是否已经打开。

提前致谢。

4

1 回答 1

2

除了打开和关闭之外,还有连接状态:Broken、Closed、Connecting、Executing、Fetching。你应该只在它“关闭”时尝试打开。如果有其他情况,则需要以不同方式处理。

于 2012-04-15T21:50:26.470 回答