user_id = (101,) # Note: Must be a tuple cursor.execute("SELECT * FROM users WHERE id = ?", user_id) user = cursor.fetchone() print(user) Use code with caution. 3. Fixing the "Data Not Saving" Issue
cursor.execute("INSERT INTO users (name, age) VALUES (?, ?)", ("Alice", 30)) # WITHOUT THIS, YOUR DATA IS LOST: connection.commit() Use code with caution. 4. Handling "Database is Locked" Errors
The first step to a "fixed" implementation is ensuring your connection and cursor are handled properly. sqlite3 tutorial query python fixed
with sqlite3.connect('app_data.db') as conn: cursor = conn.cursor() cursor.execute("SELECT * FROM users") # No need to call commit() manually for simple operations here; # the context manager handles the transaction. Use code with caution. 5. Efficiently Fetching Query Results
When connecting, give SQLite more time to wait for a lock to clear. conn = sqlite3.connect('app_data.db', timeout=10) user_id = (101,) # Note: Must be a tuple cursor
This ensures the connection closes even if an error occurs.
If you are accessing the database from multiple threads or have an unclosed connection in another script, you’ll see sqlite3.OperationalError: database is locked . Use code with caution
SQLite3 uses ? as a placeholder. This ensures the library handles escaping and data types for you.
import sqlite3 # Connect to a database (creates it if it doesn't exist) connection = sqlite3.connect('app_data.db') # Create a cursor object to execute SQL commands cursor = connection.cursor() Use code with caution. 2. The "Fixed" Way to Handle Queries: Parameterization