2017-02-09 45 views
0

我的SQLite查詢掛起,然後在下面的WriteToDB()的ExecuteNonQuery()中鎖定。它似乎只在UPDATE期間鎖定,並且與INSERT沒有問題。這隻能在一個線程中運行。當它掛起時,我可以看到正在SQLite數據庫目錄中創建的日誌,就好像它不斷嘗試寫入一樣。它拋出一個SQLiteException,ErrorCode = 5,ResultCode = Busy。更新過程中的C#SQLite數據庫

public String WriteToDB() 
    { 
     String retString = ""; 

     //see if account exists with this email 
     String sql = ""; 
     bool aExists = AccountExists(); 

     if (!aExists) 
     { 
      sql = "INSERT INTO accounts (email, password, proxy, type, description) VALUES ('" + Email + "', '" + Password + "', '" + Proxy + "', 'dev', '" + Description + "');"; 
      retString = "Added account"; 
     } 
     else 
     { 
      sql = "UPDATE accounts SET password='" + Password + "', proxy='" + Proxy + "', description='" + Description + "' WHERE (email='" + Email + "' AND type='dev');"; 
      retString = "Updated account"; 
     } 

     using (SQLiteConnection dbconn = new SQLiteConnection("Data Source=" + Form1.DBNAME + ";Version=3;")) 
     { 
      dbconn.Open(); 
      using (SQLiteCommand sqlcmd = new SQLiteCommand(sql, dbconn)) 
      { 
       sqlcmd.ExecuteNonQuery(); //this is where it locks. Only on update. 
      } 
     } 
     return retString; 
    } 

    //Test to see if Email exists as account 
    public bool AccountExists() 
    { 
     int rCount = 0; 
     String sql = "SELECT COUNT(email) FROM accounts WHERE email='" + Email + "' AND type='dev';"; 
     using (SQLiteConnection dbconn = new SQLiteConnection("Data Source=" + Form1.DBNAME + ";Version=3;")) 
     { 
      dbconn.Open(); 
      using (SQLiteCommand sqlcmd = new SQLiteCommand(sql, dbconn)) 
      { 
       rCount = Convert.ToInt32(sqlcmd.ExecuteScalar()); 
      } 
     } 
     if (rCount > 0) 
      return true; 
     return false; 
    } 
+0

剛剛掛了?沒有像「連接已經打開」的錯誤? – Sergio

+2

代碼5通常表示連接已經打開。我個人喜歡在應用程序運行時保持與SQLite打開的連接,並且只在應用程序關閉時關閉它。 SQLite是無服務器,這意味着它只是一個文件,每次打開它對我沒有太大意義 – Alex

+0

可能更新命令試圖在帳戶表上寫入,而AccountExists函數的select命令仍被認爲是活動的。首先嚐試在WriteTODB函數內重新打開代碼而不打開第二次連接 – jambonick

回答

0

哦,我覺得很愚蠢。我以爲我發佈了所有相關的代碼,但是我發佈的所有代碼都很好。我:

SQLiteDataReader dbReader = sqlcmd.ExecuteReader() 

,而不是

using (SQLiteDataReader dbReader = sqlcmd.ExecuteReader()) 

在另一個功能。我認爲這是UPDATE的問題,因爲那是發生鎖定的地方。感謝您的回覆,並希望這個提醒提醒大家第一次在SQLite中使用()塊!