2012-10-09 146 views
-1

我想連接到一個MySQL數據庫,我的憑據(用戶名,密碼,數據庫名稱等)都是正確的,據我所知。我被困在coonection.open()語句中,該語句顯示已經打開連接的錯誤。無法連接到MySQL的C#,連接已打開錯誤

我搜索了在其他網站的幫助下,它已被報告爲一個錯誤... 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(); 
     } 
    } 

    } 

} 
+0

您可以將您的代碼發佈到初始化DbConnect並調用DbConnect方法的位置嗎? –

回答

5

您必須關閉連接,你有(後也許第一次調試)未關閉的連接

您可以使用

connection.Close(); 

最佳實踐:

我建議你使用使用塊,以確保您在處理結束時清理非管理對象

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