Sqlite3 Tutorial Query Python Fixed Jun 2026
Use an absolute path to ensure Python always points to the exact same database file.
cursor.execute('SELECT * FROM inventory WHERE quantity > 0') rows = cursor.fetchall() for row in rows: print(row)
# Close connection conn.close()
import sqlite3 try: # 1. Establish the connection conn = sqlite3.connect('library.db') cursor = conn.cursor() # 2. Execute the query cursor.execute("INSERT INTO books (title, author) VALUES (?, ?)", ('The Great Gatsby', 'F. Scott Fitzgerald')) # 3. THE FIX: Commit the changes! conn.commit() print("Success! The book is in the shelf.") except sqlite3.Error as e: print(f"An error occurred: e") finally: # 4. Always close the connection if conn: conn.close() Use code with caution. Copied to clipboard The Happy Ending sqlite3 tutorial query python fixed
You can enable autocommit by passing isolation_level=None :
def get_all_employees(): try: with sqlite3.connect('company.db') as conn: # This allows accessing columns by name (row['name']) conn.row_factory = sqlite3.Row cursor = conn.cursor() cursor.execute("SELECT * FROM employees")
# fetch one cur.execute("SELECT id, name, email FROM users WHERE email = ?", ("alice@example.com",)) row = cur.fetchone() if row: id, name, email = row Use an absolute path to ensure Python always
(1, 'John Doe', 'john@example.com') (2, 'Jane Doe', 'jane@example.com') (3, 'Bob Smith', 'bob@example.com')
For testing purposes, you can use :memory: as the database name to create a temporary database that exists only in RAM. 2. Creating a Table
Always wrap single query arguments into a trailing with a comma (variable,) . Execute the query cursor
Now, let's connect to the example.db database using Python:
with sqlite3.connect("app_database.db") as connection: cursor = connection.cursor() # Create a table cursor.execute(""" CREATE TABLE IF NOT EXISTS users ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, email TEXT UNIQUE NOT NULL, age INTEGER ) """) # Insert a single record cursor.execute(""" INSERT INTO users (name, email, age) VALUES ('Alice Smith', 'alice@example.com', 30) """) # Save (commit) the changes connection.commit() Use code with caution. 3. How to Query Data Correctly
cursor.execute('SELECT title, rating FROM books ORDER BY rating DESC LIMIT 3') top3 = cursor.fetchall()