2017-12-18 171 views
0

我打開一個帶有C#WinForm的SQLite數據庫,並試圖處理異常,並得到一個奇怪的錯誤。我已經實現這個代碼使用SQLite ADO.Net初始化C#表單時出錯以及錯誤檢查

bool TryingtoStart = true; 

while (TryingtoSTart) 
{ 
    try 
     { 
      dbc.Open(); 

       departmentDataAdapter = new SQLiteDataAdapter("select * from DEPARTMENT", dbc); 
       // etc 
     } 

     catch (SQLiteException ex) 
     { 
       DialogResult r = MetroFramework.MetroMessageBox.Show(this, ex.Message.ToString(), "Database error", MessageBoxButtons.RetryCancel); 

       if (r == DialogResult.Cancel) TryingtoStart = false; 
     } 

     catch (Exception exc) 
     { 
       DialogResult r = MetroFramework.MetroMessageBox.Show(this, exc.Message.ToString(), "Exception", MessageBoxButtons.RetryCancel); 
       if (r == DialogResult.Cancel) TryingtoStart = false; 
     } 

     if (!TryingtoStart) Application.Exit(); 
} 

並且得到錯誤

"Operation is not valid due to the current state of the object." 

時運行。這來自第二個catch(),即它不是一個SQLException。如果我刪除我抓,我得到的錯誤

System.InvalidOperationException: Operation is not valid due to the current state of the object. 
    at System.Data.SQLite.SQLiteConnection.Open() 

用open()的行號調用

如果我刪除while循環的try/catch語句,這一切工作正常。此代碼位於Form_Load()方法中。

我已經嘗試過,但無法理解這一點。我幾次評論/取消評論,並且錯誤是一致的。

+0

doh!謝謝Zhar。會測試像if(dbc.State == ConnectionState.Open)break;工作好嗎?似乎有幾個國家的連接可以在這樣看來特別爲開放似乎安全 –

+0

檢查我的答案中的代碼。 –

回答

1

如果一切順利,沒有例外,你不會走出循環。這意味着您再次運行dbc.Open();--一旦它已經打開。
這是什麼導致異常。

順便說一句,數據適配器隱式地打開連接,如果它關閉,所以你甚至不需要dbc.Open()代碼行。

更好的實現你的代碼會是這樣的:

bool TryingtoStart = true; 

while (TryingtoSTart) 
{ 

    using(var dbc = new SQLiteConnection(connectionString)) 
    { 
     try 
     { 
      using(var departmentDataAdapter = new SQLiteDataAdapter("select * from DEPARTMENT", dbc)) 
      { 
        // etc 
      } 

      // Note: This row will only be executed if there where no exceptions until this point in the code 
      TryingtoStart = false; 
     } 

     catch (SQLiteException ex) 
     { 

      if (MetroFramework.MetroMessageBox.Show(this, ex.Message.ToString(), "Database error", MessageBoxButtons.RetryCancel) == DialogResult.Cancel) Application.Exit(); 
     } 
     catch (Exception exc) 
     { 
      if (MetroFramework.MetroMessageBox.Show(this, exc.Message.ToString(), "Exception", MessageBoxButtons.RetryCancel) == DialogResult.Cancel) Application.Exit(); 
     } 
    } 
} 

注意我創建兩個SQLiteConnectionSQLiteDataAdapter一個using語句中 - 因爲它們都實現IDisposable接口。

+0

謝謝!這好多了。知道數據適配器打開連接也很好。 –