我收到来自 SQLite 的 Database is locked 异常,仅针对某些查询。
下面是我的代码:
当我执行任何 select 语句时,它工作正常。
当我在 Jobs
表上执行任何写语句时,它也能正常工作。
这很好用:
ExecuteNonQuery("DELETE FROM Jobs WHERE id=1");
但如果我正在执行对 Employees
表的查询,它会抛出一个异常,表明数据库已锁定。
这会抛出异常:
ExecuteNonQuery("DELETE FROM Employees WHERE id=1");
以下是我的功能:
public bool OpenConnection()
{
if (Con == null)
{
Con = new SQLiteConnection(ConnectionString);
}
if (Con.State == ConnectionState.Closed)
{
Con.Open();
//Cmd = new SQLiteCommand("PRAGMA FOREIGN_KEYS=ON", Con);
//Cmd.ExecuteNonQuery();
//Cmd.Dispose();
//Cmd=null;
return true;
}
if (IsConnectionBusy())
{
Msg.Log(new Exception("Connection busy"));
}
return false;
}
public Boolean CloseConnection()
{
if (Con != null && Con.State == ConnectionState.Open)
{
if (Cmd != null) Cmd.Dispose();
Cmd = null;
Con.Close();
return true;
}
return false;
}
public Boolean ExecuteNonQuery(string sql)
{
if (sql == null) return false;
try
{
if (!OpenConnection())
return false;
else
{
//Tx = Con.BeginTransaction(IsolationLevel.ReadCommitted);
Cmd = new SQLiteCommand(sql, Con);
Cmd.ExecuteNonQuery();
//Tx.Commit();
return true;
}
}
catch (Exception exception)
{
//Tx.Rollback();
Msg.Log(exception);
return false;
}
finally
{
CloseConnection();
}
}
这是异常(exception):
在第 103 行:Cmd.ExecuteNonQuery();
Exception Found: Type: System.Data.SQLite.SQLiteException Message: database is locked database is locked Source: System.Data.SQLite
Stacktrace: at System.Data.SQLite.SQLite3.Step(SQLiteStatement stmt) at System.Data.SQLite.SQLiteDataReader.NextResult() at System.Data.SQLite.SQLiteDataReader..ctor(SQLiteCommand cmd, CommandBehavior behave) at System.Data.SQLite.SQLiteCommand.ExecuteReader(CommandBehavior behavior) at System.Data.SQLite.SQLiteCommand.ExecuteNonQuery() at TimeSheet6.DbOp.ExecuteNonQuery(String sql) in d:\Projects\C# Applications\Completed Projects\TimeSheet6\TimeSheet6\DbOp.cs:line 103
最佳答案
某处连接一直处于打开状态。摆脱 OpenConnection
和 CloseConnection
并将 ExecuteNonQuery
更改为:
using (SQLiteConnection c = new SQLiteConnection(ConnectionString))
{
c.Open();
using (SQLiteCommand cmd = new SQLiteCommand(sql, c))
{
cmd.ExecuteNonQuery();
}
}
此外,将您读取数据的方式更改为:
using (SQLiteConnection c = new SQLiteConnection(ConnectionString))
{
c.Open();
using (SQLiteCommand cmd = new SQLiteCommand(sql, c))
{
using (SQLiteDataReader rdr = cmd.ExecuteReader())
{
...
}
}
}
不要尝试像您在这里一样自行管理连接池。首先,它比您编写的代码复杂得多,但其次,它已经在 SQLiteConnection
对象中进行了处理。最后,如果您没有利用using
,您就没有正确处理这些对象,最终会遇到像您现在看到的那样的问题。
关于c# - SQLite 数据库锁定异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17592671/