gpt4 book ai didi

c# - Sqlite 数据库被锁定

转载 作者:行者123 更新时间:2023-11-30 16:36:11 25 4
gpt4 key购买 nike

我正在使用 asp.net c# 并将 SqLite 数据库上传到服务器,然后进行一些插入和更新。问题是有时(我认为是更新出现问题时)数据库被锁定。所以下次我尝试再次上传文件时,它被锁定了,我收到一条错误消息“该进程无法访问该文件,因为它正被另一个进程使用”。如果在交易过程中出现问题,数据库文件可能不会被处理?解决这个问题的唯一方法是重新启动服务器。

如何在我的代码中解决它,以便即使出现问题我也能确保它始终解锁?

这是我的代码:

try
{
string filepath = Server.MapPath("~/files/db.sql");

//Gets the file and save it on the server
((HttpPostedFile)HttpContext.Current.Request.Files["sqlitedb"]).SaveAs(filepath);

//Open the database
SQLiteConnection conn = new SQLiteConnection("Data Source=" + filepath + ";Version=3;");

conn.Open();
SQLiteCommand cmd = new SQLiteCommand(conn);
using (SQLiteTransaction transaction = conn.BeginTransaction())
{
using (cmd)
{
//Here I do some stuff to the database, update, insert etc
}
transaction.Commit();
}
conn.Close();
cmd.Dispose();
}
catch (Exception exp)
{
//Error
}

最佳答案

您也可以尝试将 Connection 放在 using block 中,或对其调用 Dispose:

//Open the database
using (SQLiteConnection conn = new SQLiteConnection("Data Source=" + filepath + ";Version=3;")) {
conn.Open();
using (SQLiteCommand cmd = new SQLiteCommand(conn)) {
using (SQLiteTransaction transaction = conn.BeginTransaction()) {
//Here I do some stuff to the database, update, insert etc
transaction.Commit();
}
}
}

这将确保您正确处理连接对象(您现在不是,只是关闭它)。

将它们包装在 using block 中可确保即使发生异常也会调用 Dispose - 这实际上与编写相同:

// Create connection, command, etc objects.
SQLiteConnection conn;

try {
conn = new SQLiteConnection("Data Source=" + filepath + ";Version=3;");
// Do Stuff here...
}
catch (exception e) {
// Although there are arguments to say don't catch generic exceptions,
// but instead catch each explicit exception you can handle.
}
finally {
// Check for null, and if not, close and dispose
if (null != conn)
conn.Dispose();
}

无论异常如何,finally block 中的代码都会被调用,并帮助您清理。

关于c# - Sqlite 数据库被锁定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1166265/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com