【问题标题】:Connecting to MySQL database with C#使用 C# 连接到 MySQL 数据库
【发布时间】:2012-04-27 07:52:45
【问题描述】:

我正在使用:

        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。这没有意义,因为我检查它是否已经打开。

提前致谢。

【问题讨论】:

    标签: c# mysql database ado.net mysql-connector


    【解决方案1】:

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

    【讨论】:

    • @user1335122 在 if 语句之前打印连接状态。这可能会给你一些关于状态的信息。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-28
    • 1970-01-01
    • 2013-08-18
    • 2014-01-19
    相关资源
    最近更新 更多