2

I am using Python 3 and sqlite3 on Windows. I am developing a small application that is using a database to store contacts. I notice that if the application closes forcibly (either by error or ending via task manager) that I get the sqlite3 error (sqlite3.OperationalError: database is locked).

I imagine this is because I am not properly closing the database connection before the application has closed. I have tried this:

    connection = sqlite3.connect(dbFile.db)
    connection.commit()
    connection.close()

and then trying to reopen the connection, but the locked database remains. Is there anyway to close the database before a crash? Or a way to unlock the database in the application? Right now the only solution I have is to delete the database and start over (which will not really work long term).

Thanks!

  • is the file in a mounted directory? sometime that can be an issue – MEdwin Mar 25 '19 at 09:03
  • The file is on a secondary hard drive (d). This could be the case. Is there any means of avoiding this or should I always save these files on the c drive. Thanks! – SpaceyEeyore Mar 26 '19 at 00:25

1 Answers1

0

If your application closes forcibly, surly you wouldn't want to commit your current transaction, instead rollback to insure nothing breaks?

After a signal for a close has been caught, try the following:

connection.rollback()
connection.close()
Alex Hodges
  • 607
  • 1
  • 5
  • 9
  • the code except I had found somewhere else (you're definitely right in that I don't want to commit, I am simply trying to release the lock). The issue I'm having is when developing this application I may not have caught an error and the application already has forcibly closed and want a way to unlock or reset without having to delete the file. – SpaceyEeyore Mar 26 '19 at 00:24
  • Check out [this](https://stackoverflow.com/questions/151026/how-do-i-unlock-a-sqlite-database). It seem that your program dying during an operation that locks the database is undefined behaviour. Options I could suggest: Improve error handling in your program to insure you dont forcibly quit during a heavy sql operation. After an unexpected quit, on startup have your program check if there is a process using the database, and kill it. – Alex Hodges Apr 01 '19 at 12:00
  • That is a good suggestion. I think it would be wise to better error handling, issue arises during my debugging sessions when I have been adding new code and wanting to test a new feature. – SpaceyEeyore Apr 02 '19 at 19:06