我打開一個帶有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()方法中。
我已經嘗試過,但無法理解這一點。我幾次評論/取消評論,並且錯誤是一致的。
doh!謝謝Zhar。會測試像if(dbc.State == ConnectionState.Open)break;工作好嗎?似乎有幾個國家的連接可以在這樣看來特別爲開放似乎安全 –
檢查我的答案中的代碼。 –