🧚 注目!Beekeeper Studioは高速でモダン、オープンソースのデータベースGUIです ダウンロード
June 25, 2024 著者: Matthew Rathbone

Introduction

SQLite uses file-level locking to manage access to the database file on disk. The “database is locked” error occurs when one process tries to access the database while another is actively writing to it. This situation can arise in various scenarios, such as:

  • Multiple applications accessing the database at the same time.
  • Long-running transactions that do not commit or rollback promptly.
  • Improper handling of database connections and cursors.

Tip: When investigating SQLite errors like "database is locked", it helps to open and inspect your database visually.

With a desktop SQL client such as Beekeeper Studio, you can open your .db file, browse tables, and re-run queries interactively to confirm that your changes are working.

How to Resolve the Error

Solution 1: Ensure Proper Transaction Management

Improper transaction handling can often lead to a locked database. Ensure that transactions are completed promptly by committing or rolling back as appropriate.

Example:

BEGIN TRANSACTION;
-- Insert data into the table
INSERT INTO employees (name, position) VALUES ('John Doe', 'Software Engineer');
-- Commit the transaction
COMMIT;

Expected Output:

No output, but the transaction completes successfully without locking the database.

After committing, it’s good practice to confirm that your database accepts new writes.

The screenshot below shows a similar check in Beekeeper Studio: an INSERT followed by a SELECT verifies that new data (in this case, a record for “Maria Lopez”) was written successfully.

Beekeeper Studio showing a successful SQL insert and select query on an SQLite database, confirming that new rows can be written after resolving a lock.

Solution 2: Use Database Connection Properly

Always close the database connection properly after operations are completed. This prevents the database from being unnecessarily locked.

Example:

import sqlite3
from contextlib import closing

database_path = 'mydatabase.db'

with closing(sqlite3.connect(database_path)) as conn:
    with closing(conn.cursor()) as cursor:
        cursor.execute("INSERT INTO employees (name, position) VALUES (?, ?)", ('Jane Doe', 'Project Manager'))
    conn.commit()

Expected Output:

No output, but the insert operation is performed without locking the database, and the connection is closed properly.

If you prefer using a GUI over code, Beekeeper Studio automatically opens and closes SQLite connections for you each time you run a query, reducing the risk of leaving a database locked.

Solution 3: Configure Timeout

Setting a timeout duration can help in scenarios where multiple accesses are expected. This tells SQLite how long to wait before returning a “database is locked” error, giving the lock a chance to be released.

Example:

import sqlite3

conn = sqlite3.connect('mydatabase.db', timeout=10.0)  # Set timeout to 10 seconds
cursor = conn.cursor()

try:
    cursor.execute("INSERT INTO employees (name, position) VALUES (?, ?)", ('Sam Smith', 'Data Analyst'))
finally:
    cursor.close()
    conn.close()

Expected Output:

No output, but the timeout provides a window for overcoming temporary locks.

Tip: In Beekeeper Studio, you can re-run a query that previously failed with a “database is locked” error to confirm whether a timeout or retry has resolved the issue. It’s a quick way to test changes without editing code.

Solution 4: Avoid Long-Running Transactions

Keep transactions short to minimize the time the database is locked. This reduces the likelihood of encountering the “database is locked” error.

Example:

BEGIN TRANSACTION;
INSERT INTO employees (name, position) VALUES ('Alice Johnson', 'HR Manager');
COMMIT;

Expected Output:

No output, but the transaction completes swiftly, reducing the lock duration.

Conclusion

The “SQLite database is locked” error is typically a symptom of concurrency issues or mismanagement of database connections and transactions. By following the best practices outlined above, such as managing transactions efficiently, using connections properly, setting appropriate timeouts, and avoiding long-running transactions, you can prevent this error from occurring. These strategies ensure that your SQLite database operations are both robust and efficient.

Try it yourself

You can open any .db file in Beekeeper Studio to explore tables, run queries, and confirm that your changes are applied correctly. It’s open source, connects to 20+ databases, and works perfectly on Windows, macOS, and Linux.

Download Beekeeper Studio →

Beekeeper Studioは無料でオープンソースのデータベースGUIです

今まで使った中で最高のSQLクエリ&エディタツールです。データベース管理に必要なすべてが揃っています。 - ⭐⭐⭐⭐⭐ Mit

Beekeeper Studioは高速で直感的、使いやすいです。Beekeeperは多くのデータベースをサポートし、Windows、Mac、Linuxで快適に動作します。

BeekeeperのLinux版は100%フル機能で、機能の妥協はありません。

Beekeeper Studioについてユーザーの声

★★★★★
"Beekeeper Studioは私の古いSQLワークフローを完全に置き換えました。高速で直感的で、データベース作業を再び楽しくしてくれます。"
— Alex K.、データベース開発者
★★★★★
"多くのデータベースGUIを試しましたが、Beekeeperは機能とシンプルさの完璧なバランスを実現しています。とにかく動きます。"
— Sarah M.、フルスタックエンジニア

SQLワークフローを改善する準備はできましたか?

download 無料ダウンロード