简体   繁体   中英

sqlite database is locked exception

I am using c# application and running the application in server machine as windows service.When i perform insert , update delete operation from client machine it throws database lock error as below,

database is locked
   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()
   at System.Data.SQLite.SQLiteTransaction.Commit()

Below is my code

public int ExecuteNonQuerySQL(SQLiteCommand cmd)
   {
        int ireturn = 0;
         if (conn.State != ConnectionState.Open)
               Open(DataFile);
          using (SQLiteTransaction dbtrans = conn.BeginTransaction(IsolationLevel.ReadCommitted))
            {
                  using (cmd.Connection=conn)
                    {
                         cmd.CommandText =cmd.CommandText ;
                          cmd.Transaction = dbtrans;
                           ireturn = cmd.ExecuteNonQuery();
                           dbtrans.Commit();
                           cmd.Dispose();
                        }
                   }
               }

Please help me in this , I have done lot of googling and i must find some solution to solve this . Regards

From the code provided it seems that you do not close the connecttion.

Pay attention also on fact, don't know if it's relevant in your case or not, that the Sqlite not very good on supporting concurent inserts and sometimes db got lock, if you operate on it from multiple threads.

Change the way you create your Connection and Command objects to be more like this: https://stackoverflow.com/a/17592858/8479

Make sure you're not re-using any Sqlite object on a different thread to the one it was created on.

Sqlite is normally great at concurrency provided you follow those two rules.

In my case closing the connection was not an issue. The issue was i was opening and closing connection for each Table although the database was same. So do not open connection multiple times for the same database in SQlite.

  • Open Connection
  • Do your all of your transactions in just that opened connection.
  • Close connection.

SQlite is not good at handling this. So if you cannot afford that solution its better to use a Server like SQLServer etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM