[英]Error in initializing C# form with SQLite ADO.Net and error checking
我正在使用C#WinForm打開SQLite數據庫,並嘗試處理異常,並得到一個奇怪的錯誤。 我已經實現了這段代碼
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()方法中。
我已經嘗試過,但無法理解。 我已經評論/未評論幾次,並且該錯誤是一致的。
如果在第一次嘗試中一切順利,沒有例外,您就不會退出循環。 這意味着您正在運行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();
}
}
}
注意,我在using
語句中同時創建了SQLiteConnection
和SQLiteDataAdapter
,因為它們都實現了IDisposable
接口。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.