无法从c#连接到mysql,连接已经打开错误

时间:2012-10-09 18:30:58

标签: c# .net mysql database

我正在尝试连接到mysql数据库,我的凭据(用户名,密码,数据库名称等)都是正确的。我遇到了coonection.open()语句,它显示已经打开的连接错误。

我在其他网站上搜索过帮助,但据报道它是一个错误... http://support.microsoft.com/kb/823401

在寻找替代解决方案时,我遇到了

   using ( connection = MySqlConnection(connectionString))

我无法继续下去。任何帮助都会非常感激。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MySql.Data.MySqlClient;
using System.Windows.Forms;

namespace HotelManagement
{
class DBConnect
{
    private MySqlConnection connection;
    private string server;
    private string database;
    private string uid;
    private string password;

    //constructor
    public DBConnect()
    {
        Initialize();
    }

    private void Initialize()
    {
        server = "localhost";
        database = "hm";
        uid = "root";
        password = "password";
        string connectionString;
        connectionString = "SERVER=" + server + ";" + "DATABASE=" + database + ";" +    "UID=" + uid + ";" + "PASSWORD=" + password + ";";

        connection = new MySqlConnection(connectionString);
    }

    public bool openConnection()
    {
        try
        {
            connection.Open();  //*SHOWS ERROR InvalidOperationUnhandled: Conection already open*
            return true;

        }
        catch (MySqlException e)
        {
            //error 0: Cannot Connect to the server
            switch (e.Number)
            {
                case 0: MessageBox.Show("Cannot Connect to the server");
                    break;
                case 1045: MessageBox.Show("invalid username/password");
                    break;
            }
            return false;
        }
    }

    public bool closeConnection()
    {
        try
        {
            connection.Close();
            return true;
        }
        catch (MySqlException e)
        {
            MessageBox.Show(e.Message);
            return false;
        }
    }

    public void insert()
    {
        string query = "insert into test (i) values (10)";
        if (this.openConnection() == true)
        {
            //creating command and connections
            MySqlCommand cmd = new MySqlCommand(query, connection);
            cmd.ExecuteNonQuery();
            this.closeConnection();
        }
    }

    }

}

1 个答案:

答案 0 :(得分:5)

您必须关闭连接,尚未关闭连接(可能在第一次调试后)

您可以使用

connection.Close();

最佳实践:

我建议你使用block,以确保你在治疗结束时清理非管理对象

using(var connection = new MySqlConnection(...))
{
  ...
}