2013-06-19 7 views
0

내 프로그램에 대해 mysql 연결 검사기를 만들고 싶었고 항상 평소 조언자 인 SO을 사용했는데이 Question에 착륙했습니다. 답변이 정확하지 않았습니다.MySql DB 연결 확인

질문 : C#에서 유효한 MySQL 연결을 확인하는 방법은 무엇입니까?

답변

4

여기에 mysql 연결을 확인하는 내 자신의 버전입니다.

public static bool checkDB_Conn() 
{ 
    var conn_info = "Server=address;Port=3306;Database=dbhere;Uid=admin;Pwd=123"; 
    bool isConn = false; 
    MySqlConnection conn = null; 
    try 
    { 
     conn = new MySqlConnection(conn_info); 
     conn.Open(); 
     isConn = true; 
    } 
    catch (ArgumentException a_ex) 
    { 
     /* 
     Console.WriteLine("Check the Connection String."); 
     Console.WriteLine(a_ex.Message); 
     Console.WriteLine(a_ex.ToString()); 
     */ 
    } 
    catch (MySqlException ex) 
    { 
     /*string sqlErrorMessage = "Message: " + ex.Message + "\n" + 
     "Source: " + ex.Source + "\n" + 
     "Number: " + ex.Number; 
     Console.WriteLine(sqlErrorMessage); 
     */ 
     isConn = false; 
     switch (ex.Number) 
     { 
      //http://dev.mysql.com/doc/refman/5.0/en/error-messages-server.html 
      case 1042: // Unable to connect to any of the specified MySQL hosts (Check Server,Port) 
       break; 
      case 0: // Access denied (Check DB name,username,password) 
       break; 
      default: 
       break; 
     } 
    } 
    finally 
    { 
     if (conn.State == ConnectionState.Open) 
     { 
      conn.Close(); 
     } 
    } 
    return isConn; 
} 
+5

'finally'대신'using'을 사용해야합니다. – SLaks

+0

예. "사용 중"이라는 연결이 닫히고 있음을 알지 못했습니다. 감사합니다 – Incognito

+0

내 프로젝트 오류이 코드를 compying 말한다 : 이름 'ConnectionState'현재 컨텍스트에서 존재하지 않습니다. 둘 다 MySql.Data를 사용합니다. MySql.Data.MySqlClient; 존재 ... – docesam