-1

我正在尝试连接到 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();
        }
    }

    }

}
4

1 回答 1

5

你必须关闭你的连接,你还没有关闭连接(也许在第一次调试之后)

您可以使用

connection.Close();

最佳实践:

我建议你使用 using 块,以确保你在处理结束时清理非托管对象

using(var connection = new MySqlConnection(...))
{
  ...
}
于 2012-10-09T18:34:44.643 回答