Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python SQLite: database is locked

I'm trying this code:

import sqlite  connection = sqlite.connect('cache.db') cur = connection.cursor() cur.execute('''create table item   (id integer primary key, itemno text unique,         scancode text, descr text, price real)''')  connection.commit() cur.close() 

I'm catching this exception:

Traceback (most recent call last):   File "cache_storage.py", line 7, in <module>     scancode text, descr text, price real)''')   File "/usr/lib/python2.6/dist-packages/sqlite/main.py", line 237, in execute     self.con._begin()   File "/usr/lib/python2.6/dist-packages/sqlite/main.py", line 503, in _begin     self.db.execute("BEGIN") _sqlite.OperationalError: database is locked 

Permissions for cache.db are ok. Any ideas?

like image 455
Soid Avatar asked Apr 29 '10 21:04

Soid


People also ask

How do you check if SQLite database is locked?

There's no use checking before (if that is possible), it still can get locked between the check and your next call. Better would be to make your call, and handle possible exceptions, eg. retry a number of times and report an error after too much retries.

Why is my database locked?

OperationalError: database is locked errors indicate that your application is experiencing more concurrency than sqlite can handle in default configuration. This error means that one thread or process has an exclusive lock on the database connection and another thread timed out waiting for the lock the be released.


1 Answers

I'm presuming you are actually using sqlite3 even though your code says otherwise. Here are some things to check:

  1. That you don't have a hung process sitting on the file (unix: $ fuser cache.db should say nothing)
  2. There isn't a cache.db-journal file in the directory with cache.db; this would indicate a crashed session that hasn't been cleaned up properly.
  3. Ask the database shell to check itself: $ sqlite3 cache.db "pragma integrity_check;"
  4. Backup the database $ sqlite3 cache.db ".backup cache.db.bak"
  5. Remove cache.db as you probably have nothing in it (if you are just learning) and try your code again
  6. See if the backup works $ sqlite3 cache.db.bak ".schema"

Failing that, read Things That Can Go Wrong and How to Corrupt Your Database Files

like image 90
msw Avatar answered Sep 29 '22 09:09

msw