我正在使用 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();
}
}
}
注意我在语句中同时创建了 theSQLiteConnection
和SQLiteDataAdapter
inside using
- 因为它们都实现了IDisposable
接口。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句