c# - Sqlite 数据库被锁定

标签 c# asp.net sqlite locking

我正在使用 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/

相关文章:

android - Sqlite db重新排列行

c# - 未处理的异常 : System. Xml.XPath.XPathException:表达式必须计算为节点集

c# - 打开CV : set model position using rotation and translation vector

使用 facebook 登录 ASP.NET Web api 停止工作

asp.net - 禁止使用 jquery 在所有输入文本框中输入少量字符,例如 .'<' 、 '>'

c# - 将字符串转换为正确的 URI 格式?

python - sqlite3 with python - 查询调试 - 打印最终查询

c# - ASP.NET - MySQL 批量插入每行异步响应

c# - 如何为调用同一类中其他方法的方法创建基于状态的测试?

r - 无法用RSQLite/DBI包替换SQLite表