C# 单声道+;SQLite。无法打开数据库
我有一个带有构造函数和方法的C# 单声道+;SQLite。无法打开数据库,c#,sqlite,mono,C#,Sqlite,Mono,我有一个带有构造函数和方法的DBHandler类,用于更新SQLite数据库或向其中插入新记录: public class DBHandler { private string dbName; private string tableName = "table1"; private string dbPath; public DBHandler (string _dbName) {
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);
}
DBHandler dbh=newdbhandler(“database6.db3”);
对于(int i=0;i
(buffer
只是一个字符串队列)
这通常在几次迭代(通常为8-10次)中都能正常工作,然后在string
c2.ExecuteNonQuery()中出现“无法打开数据库”异常代码>在inputODB(…)
方法中。上次使用后,似乎有什么东西(连接或命令)没有正确处理,但我不知道哪里出了问题。问题如下:
你应该用这个
using (var r = c1.ExecuteReader ()) {
r.Read ();
...
}
而不仅仅是这个
var r = c1.ExecuteReader ());
r.Read ();
...
希望你不要成为简化教程的牺牲品。可能是重复的否,那个家伙甚至一次都无法打开他的数据库。我的代码通常会执行几次,然后就崩溃了。