2014-11-24 177 views
0

我有一个DBHandler类的构造函数和方法,用于更新SQLite数据库或插入一个新的记录到其中:Mono + SQLite。无法打开数据库

public class DBHandler 
    { 
     private string dbName; 
     private string tableName = "table1"; 
     private string dbPath; 

     public DBHandler (string _dbName) 
     { 
      dbName = _dbName; 
      dbPath = Path.Combine(Directory.GetCurrentDirectory(), dbName); 

      bool exists = File.Exists (dbPath); 
      if (!exists) { 
       Mono.Data.Sqlite.SqliteConnection.CreateFile (dbPath); 
       string createQuery = "CREATE TABLE " + tableName + 
            "(" + 
            "word1," + 
            "word2," + 
            "n INT INTEGER DEFAULT 1," + 
            "PRIMARY KEY (word1, word2)" + 
            ");"; 

       using (SqliteConnection connection = new SqliteConnection (String.Format ("Data Source={0};", dbPath))) { 
        connection.Open(); 
        using (var c = connection.CreateCommand()) { 
         c.CommandText = createQuery; 
         c.ExecuteNonQuery(); 
        } 
       } 
      } 
     } 

     public void InputToDb (WordPair pair) 
     { 
      string word1 = pair.word1; 
      string word2 = pair.word2; 
      int n = pair.n; 
      int newN = 1; 

      using (SqliteConnection connection = new SqliteConnection (String.Format ("Data Source={0};", dbPath))) { 
       connection.Open(); 

       using (var c1 = connection.CreateCommand()) { 
        c1.CommandText = "SELECT n from " + tableName + " WHERE word1 = '" + word1 + "' AND word2 = '" + word2 + "';"; 
        var r = c1.ExecuteReader(); 
        r.Read(); 
        if (!r.HasRows) 
         newN = 1; 
        else 
         newN = int.Parse (r ["n"].ToString()) + 1; 
       } 
      } 

      using (SqliteConnection connection = new SqliteConnection (String.Format ("Data Source={0};", dbPath))) { 
       connection.Open(); 
       using (var c2 = connection.CreateCommand()) { 
        string inputQuery = "INSERT OR REPLACE INTO " + tableName + " (word1, word2, n) " + 
             "VALUES ('" + word1 + "', " + 
             "'" + word2 + "', " + 
             newN.ToString() + 
             ");"; 
        c2.CommandText = inputQuery; 
        c2.ExecuteNonQuery(); 
       } 
      } 
     } 
} 

这是类的使用方法如下:

DBHandler dbh = new DBHandler ("database6.db3"); 
for (int i = 0; i < buffer.Count-1; i++) { 
    WordPair tempPair = new WordPair (buffer.Dequeue(), buffer.Peek(), 1); 
    dbh.InputToDb (tempPair); 
} 

buffer只是一串字符串)

这对于少数迭代(通常是8-10)总是可以正常工作,然后用字符串中的“无法打开数据库”异常在InputToDb(...)方法中。它看起来像(连接或命令)在上次使用后没有正确处理,但我不知道哪里出了问题。

+0

[单声道无法打开sqlite数据库]的可能的副本(http://stackoverflow.com/questions/12648217/mono-cant-open-sqlite-database) – MethodMan 2014-11-24 20:39:13

+0

不,那家伙甚至无法打开他的数据库一旦。我的代码通常会执行几次,然后崩溃。 – 2014-11-25 12:13:48

回答

1

问题是以下几点:

应该使用这个

using (var r = c1.ExecuteReader()) { 
    r.Read(); 
    ... 
} 

,而不仅仅是这个

var r = c1.ExecuteReader()); 
r.Read(); 
... 

希望你不要成为简单的教程的受害者。