SQLite may lock database resources when another connection or process performs a transaction. If an operation cannot proceed until the lock is released, SQLite waits for the configured timeout period before reporting an error.
Syntax
sqlite3.connect("database.db", timeout=20.0)
- database.db: Specifies the SQLite database file.
- timeout: Sets the maximum lock-wait duration in seconds.
Example: In following code, we set the connection timeout to 20 seconds while connecting to an SQLite database.
import sqlite3
sqliteConnection = None
try:
sqliteConnection = sqlite3.connect(
"sqlite.db",
timeout=20.0
)
print("Database connected successfully.")
except sqlite3.Error as error:
print("Error occurred:", error)
finally:
if sqliteConnection is not None:
sqliteConnection.close()
print("SQLite connection closed.")
Output
Database connected successfully.
SQLite connection closed.
Explanation:
- import sqlite3 imports Python's built-in SQLite module.
- sqlite3.connect() opens a connection to sqlite.db. If the database file does not exist, SQLite creates it.
- timeout=20.0 configures the connection to wait for up to 20 seconds when an operation is blocked by a database lock.
- try-except block handles SQLite-related errors.
- Finally block closes the connection if it was successfully created.
Choosing a Timeout Value
Appropriate timeout depends on how long database transactions typically take.
- Use the default value of 5 seconds for ordinary applications.
- Increase the value when legitimate transactions may hold locks for longer periods
- Use a value of 0 when operations should not wait for a database lock.
- Avoid setting an unnecessarily long timeout, as it can delay error handling when a lock is not released.