Sqlite3 Tutorial Query Python Fixed
with conn: conn.execute("INSERT INTO users (name) VALUES (?)", ('Alice',)) conn.execute("UPDATE users SET age = 31 WHERE name = 'Alice'")
(1, 'John Doe', 'john@example.com') (2, 'Jane Doe', 'jane2@example.com')
Alex ran the script. The terminal remained silent for a heartbeat before printing: Success! The book is in the shelf. sqlite3 tutorial query python fixed
@contextmanager def get_db_connection(db_path: str = "example.db"): conn = sqlite3.connect(db_path) conn.row_factory = sqlite3.Row # Access columns by name try: yield conn conn.commit() except Exception as e: conn.rollback() raise e finally: conn.close()
cursor.execute("INSERT INTO users (name) VALUES ('John')") conn.close() # Oops! No commit – John disappears with conn: conn
username = "O'Connor" # WRONG: This crashes due to the single quote and invites SQL injection cursor.execute(f"SELECT * FROM users WHERE name = 'username'") Use code with caution. The Fix: Use Parameterized Queries
Change the row_factory property of your connection to sqlite3.Row . This allows you to access columns by their structural names, much like a Python dictionary. connection = sqlite3.connect("app.db") This allows you to access columns by their
cursor.execute(''' CREATE TABLE IF NOT EXISTS users ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, age INTEGER, email TEXT UNIQUE ) ''') conn.commit()
:
# Select all users cursor.execute('SELECT * FROM users') results = cursor.fetchall() for row in results: print(row)