Sqlite database is locked

I use asp.net C # and upload the SqLite database to the server, and then I insert and update. The problem is that sometimes (I think when something goes wrong with the update or so), the database is locked. Therefore, the next time I try to download the file again, it is blocked, and I get the error message "The process cannot access the file because it is being used by another process." Maybe the database file will not be deleted if something goes wrong during the transaction? The only thing that can be solved is to restart the server.

How can I solve this in my code so that I can be sure that it is always unlocked, even if something goes wrong?

This is my code:

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
}
+3
4

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();
    }
  }
}

( , ).

, 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 .

+2
+1

cmd.Dispose() conn.Close()? , - , , , .

0
0

Source: https://habr.com/ru/post/1713250/


All Articles