正如我可以从SQLite FAQ读取的那样,它支持多个进程读取(SELECT),并且在任何时刻都只支持一个进程写入(INSERT,UPDATE,DELETE)数据库:
SQLite使用读取器/写入器锁来控制对数据库的访问。 当任何进程想要写入时,它必须锁定整个数据库文件 在更新期间。但这通常只需要几个 毫秒。其他进程只需等待编写器完成 继续他们的业务
我通过c#使用System.Data.SQLite适配器。
有人可以告诉我PLZ,完全这个过程是怎么回事?
此过程是否会自动运行,如果还有另一个写入 SQLiteCommand 已经在同一个数据库上执行,那么编写 SQLiteCommand 会等待吗?
或许它会引发异常?什么样的?
很抱歉,但我没有找到有关此机制的信息:)
谢谢。
更新
我发现帖子说exception will be raised带有特定的错误代码
该陈述是否正确?
答案 0 :(得分:10)
我自己调查了一下:
我创建了一个示例SQLite数据库c:\123.db
,其中一个表Categories
包含两个字段:ID
(uniqueidentifier)和Name
(nvarchar)。
然后我写了一些多线程代码来模拟对数据库的多次写访问(如果你使用这段代码,不要忘记为你的项目添加System.Data.SQLite
引用):
using System;
using System.Data.SQLite;
using System.Threading.Tasks;
namespace SQLiteTest
{
class Program
{
static void Main(string[] args)
{
var tasks = new Task[100];
for (int i = 0; i < 100; i++)
{
tasks[i] = new Task(new Program().WriteToDB);
tasks[i].Start();
}
foreach (var task in tasks)
task.Wait();
}
public void WriteToDB()
{
try
{
using (SQLiteConnection myconnection = new SQLiteConnection(@"Data Source=c:\123.db"))
{
myconnection.Open();
using (SQLiteTransaction mytransaction = myconnection.BeginTransaction())
{
using (SQLiteCommand mycommand = new SQLiteCommand(myconnection))
{
Guid id = Guid.NewGuid();
mycommand.CommandText = "INSERT INTO Categories(ID, Name) VALUES ('" + id.ToString() + "', '111')";
mycommand.ExecuteNonQuery();
mycommand.CommandText = "UPDATE Categories SET Name='222' WHERE ID='" + id.ToString() + "'";
mycommand.ExecuteNonQuery();
mycommand.CommandText = "DELETE FROM Categories WHERE ID='" + id.ToString() + "'";
mycommand.ExecuteNonQuery();
}
mytransaction.Commit();
}
}
}
catch (SQLiteException ex)
{
if (ex.ReturnCode == SQLiteErrorCode.Busy)
Console.WriteLine("Database is locked by another process!");
}
}
}
}
我的Core2Duo E7500的结果是永远不会出现异常!
看起来SQLite已根据我的需求进行了优化(锁定/解锁非常快,通常只需要几毫秒,SQLite FAQ告诉我们) - 太棒了!
请注意,无需为SQLiteException
检索整数ErrorCode - 您可以使用特殊的枚举ReturnCode
字段。所有代码均为here。
希望这些信息对某人有所帮助。