2017-12-18 2 views
0

SQLite 데이터베이스를 C# WinForm으로 열고 예외 처리 및 이상한 오류가 발생했습니다. 이 코드를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이 아닙니다. 내이나 저전압을 제거하면, 나는 은 try/캐치, 모든 것이 잘 작동 while 루프를 제거하면

()를 호출 오픈의 행 번호와 오류를

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

를 얻을. 이 코드는 Form_Load() 메서드에 있습니다.

나는 이것을 시도했지만 이해할 수 없다. 나는 몇 번 주석 처리하고 주석 처리를 해본 결과 오류가 일관되었다.

+0

doh! Zohar에게 감사드립니다. if (dbc.State == ConnectionState.Open)와 같은 테스트가 중단됩니다. 잘 했어? 연결할 수있는 몇 가지 상태가 될 것으로 보인다 특히 열려 찾고 안전을 위해 –

+0

내 대답에 코드를 확인하십시오. –

답변

1

첫 번째 시도에서 예외없이 잘 진행되면 루프에서 빠져 나가지 않습니다. 다시 말하면 dbc.Open();이 다시 실행 중임을 의미합니다.
이것은 예외의 원인입니다.

사실 데이터 어댑터가 닫히면 연결이 암시 적으로 열리므로 dbc.Open() 코드 줄이 필요하지 않습니다. 코드의

더 나은 구현은 다음과 같이 될 것이다 : 나는 모두 SQLiteConnectionusing 문 내부의 SQLiteDataAdapter을 만드는거야

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(); 
     } 
    } 
} 

주 - 그들이 IDisposable 인터페이스를 구현하는 두 있기 때문이다.

+0

감사합니다. 이것은 훨씬 낫다. 연결을 여는 데이터 어댑터에 대해서도 알아두면 좋습니다. –

관련 문제