2012-10-09 4 views
-1

mysql 데이터베이스에 연결하려고합니다. 내 자격 증명 (사용자 이름, 암호, 데이터베이스 이름 ... 등)이 모두 정확합니다. coonection.open() 문에 연결이 끊어져 이미 열려있는 오류가 표시됩니다.C#에서 mysql에 연결할 수 없습니다. 이미 열려있는 오류입니다.

내가 다른 사이트에서 도움을 검색

, 그것은 다른 솔루션을 검색하는 동안

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(...)) 
{ 
    ... 
} 
관련 문제