2012-04-15 193 views
2

我使用:連接到MySQL數據庫與C#

 if (connection.State != ConnectionState.Open) 
     { 
      OpenConnection(); 
     } 

private bool OpenConnection() 
{ 
    try 
    { 
     connection.Open(); 
     return true; 
    } 
    catch (MySqlException ex) 
    { 
     //When handling errors, you can your application's response based 
     //on the error number. 
     //The two most common error numbers when connecting are as follows: 
     //0: Cannot connect to server. 
     //1045: Invalid user name and/or password. 
     switch (ex.Number) 
     { 
      case 0: 
       Console.WriteLine("Cannot connect to server. Contact administrator"); 
       Console.Read(); 
       break; 

      case 1045: 
       Console.WriteLine("Invalid username/password, please try again"); 
       Console.Read(); 
       break; 
     } 
     return false; 
    } 
} 

我總是System.InvalidOperationException: The connection is already open。它沒有意義,因爲我檢查它是否已經打開。

在此先感謝。

回答

2

除了打開和關閉之外,還有其他連接狀態:斷開,關閉,連接,執行,提取。如果它「關閉」,您應該只嘗試打開。如果有其他事情需要以不同的方式處理。

+0

仍然得到相同的錯誤..... – user1335122 2012-04-15 22:02:02

+0

@ user1335122打印if語句之前的連接狀態。這可能會給你一些有關國家的信息。 – Sandeep 2012-04-16 01:21:08

1

這是我的代碼看起來

try 
    { 
     connection = new MySqlConnection(connectionString); 
     //Console.WriteLine("{0} {1}", connection.State, ConnectionState.Closed); 
     if (connection.State == ConnectionState.Closed) 
     { 
      OpenConnection(); 
     } 
     NewAddress: 
     _C = Count(); 
     InsertAddress(); 
     if (_C <= 49) { goto NewAddress; } 
    } 
    catch (Exception e) 
    { 
     Console.WriteLine(e); 
     Console.Read(); 
    } 
    finally 
    { 
     CloseConnection(); 
    } 

連接狀態等同於封閉的,但即使我註釋掉OpenConnection()還是同樣的錯誤顯示。

+0

發現連接在InsertAddress()中被關閉的解決方案我的錯誤:P – Madmadmax 2012-04-16 16:52:39