def add_task(self, title, description='', due_date=None): with sqlite3.connect(self.db_path) as conn: cursor = conn.cursor() cursor.execute(''' INSERT INTO tasks (title, description, due_date) VALUES (?, ?, ?) ''', (title, description, due_date)) return cursor.lastrowid
data = [('Bob', 25), ('Carol', 32), ('Dave', 45)] cursor.executemany("INSERT INTO users (name, age) VALUES (?, ?)", data) conn.commit()
import unittest
def add_user(name, email): with db_connection() as conn: cursor = conn.cursor() cursor.execute( "INSERT INTO users (name, email) VALUES (?, ?)", (name, email) ) return cursor.lastrowid
cursor.execute('UPDATE characters SET health = 100 WHERE name = "Pythonia"') conn.commit() sqlite3 tutorial query python fixed
# No need to commit or close - handled automatically return results
# Correct and safe approach user_input = "O'Connor" query = "SELECT * FROM users WHERE username = ?" # Note: The parameters must be passed as a tuple or list cursor.execute(query, (user_input,)) Use code with caution. 2. The Operational Error: Single-Element Tuple Traps rating FROM books WHERE rating >
# BROKEN CODE # cursor.execute("SELECT * FROM users WHERE name = ?", "Alice") # Throws InterfaceError # FIXED CODE user_name = "Alice" cursor.execute("SELECT * FROM users WHERE name = ?", (user_name,)) Use code with caution. ProgrammingError: Incorrect number of bindings
with open("dump.sql","w") as f: for line in conn.iterdump(): f.write(f"line\n") due_date) VALUES (?
Indexes ( row[0] ) are error‑prone. Use row_factory to get dictionary‑like rows:
cursor.execute('SELECT title, rating FROM books WHERE rating > ?', (4.6,)) first_book = cursor.fetchone() print(first_book) # Output: ('The Pragmatic Programmer', 4.8)