使用SQLite ADO.Net初始化C#表单时出错以及错误检查

使用SQLite ADO.Net初始化C#表单时出错以及错误检查

问题描述:

我打开一个带有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

检查我的答案中的代码。 –

如果一切顺利,没有例外,你不会走出循环。这意味着您再次运行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

谢谢!这好多了。知道数据适配器打开连接也很好。 –