我有一个带有构造函数和方法的DBHandler
类,用于更新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次)总是正常工作,然后用&#34;无法打开数据库&#34; c2.ExecuteNonQuery ();
方法中字符串InputToDb(...)
中的异常。在上次使用之后,看起来某些东西(连接或命令)没有正确处理,但我不知道哪里出了问题。
答案 0 :(得分:1)
问题如下:
应该使用此
using (var r = c1.ExecuteReader ()) {
r.Read ();
...
}
而不仅仅是这个
var r = c1.ExecuteReader ());
r.Read ();
...
希望您不要成为简化教程的受害者。