Ulu*_*rov 4 .net c# sqlite sqlite-net
使用的 nuget 包:System.Data.SQLite.Core, 1.0.98.1
问题:在我的程序中,我在某些情况下使用启用了池和只读访问的 SQLite。通常它工作正常,但是如果对数据库有很多混合的只读/读写密集型请求,则程序会失败并出现以下异常:
Unhandled Exception: System.Data.SQLite.SQLiteException: attempt to write a readonly database
attempt to write a readonly database
at System.Data.SQLite.SQLite3.Reset(SQLiteStatement stmt)
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(CommandBehavior behavior)
at System.Data.SQLite.SQLiteCommand.ExecuteNonQuery()
Run Code Online (Sandbox Code Playgroud)
如果我禁用池化,则程序运行良好。我假设以某种方式汇集只读连接用于读写连接。我错过了什么 - 即它是否是预期的行为?
要重现的最少代码(在插入或删除时失败)。例如Thread.Sleep(10000),如果我引入延迟,它就可以正常工作。如果我删除循环,它也可以正常工作。
const string DbFilePath = "test.sqlite";
string readOnlyConnectionString = new SQLiteConnectionStringBuilder
{
DataSource = DbFilePath,
Pooling = true,
ReadOnly = true
}.ConnectionString; // data source=test.sqlite;pooling=True;read only=True
string readWriteConnectionString = new SQLiteConnectionStringBuilder
{
DataSource = DbFilePath,
Pooling = true,
ReadOnly = false
}.ConnectionString; // data source=test.sqlite;pooling=True;read only=False
File.Delete(DbFilePath);
using (SQLiteConnection conn = new SQLiteConnection(readWriteConnectionString))
using (SQLiteCommand cmd = new SQLiteCommand("CREATE TABLE items(id INTEGER NOT NULL PRIMARY KEY)", conn))
{
conn.Open();
cmd.ExecuteNonQuery();
}
while (true) // <= if we comment the loop, the program executes without error
{
using (SQLiteConnection conn = new SQLiteConnection(readWriteConnectionString))
using (SQLiteCommand cmd = new SQLiteCommand("INSERT INTO items(id) VALUES (1)", conn))
{
conn.Open();
cmd.ExecuteNonQuery();
}
using (SQLiteConnection conn = new SQLiteConnection(readOnlyConnectionString))
using (SQLiteCommand cmd = new SQLiteCommand("SELECT COUNT(*) FROM items", conn))
{
conn.Open();
cmd.ExecuteScalar();
}
using (SQLiteConnection conn = new SQLiteConnection(readWriteConnectionString))
using (SQLiteCommand cmd = new SQLiteCommand("DELETE FROM items", conn))
{
conn.Open();
cmd.ExecuteNonQuery();
}
}
Run Code Online (Sandbox Code Playgroud)
从SQLiteConnectionPool类的源代码看来,它在管理池条目时只考虑文件名。
这是一个简短的摘录:
internal static void Add(
string fileName,
SQLiteConnectionHandle handle,
int version
Run Code Online (Sandbox Code Playgroud)
没有提到使用的连接字符串,只有文件名。因此,当您需要不同的连接字符串表现出不同的行为并且单独池时,使用内置连接池机制是行不通的。
现在,作为概念的“连接池”是 ADO.NET 类层次结构的实现者自己决定的。SqlConnection 类根据唯一的连接字符串进行池化,但这绝不是 IDbConnection 的实现所必需的。
因此,这可能只是 System.Data.SQLite 的创建者做出的设计决定。但是,我会向他们发送电子邮件并询问这是否是故意的。
| 归档时间: |
|
| 查看次数: |
2607 次 |
| 最近记录: |