Sqlite3 Tutorial Query Python Fixed -
def list_tasks(): with sqlite3.connect(DB_NAME) as conn: conn.row_factory = sqlite3.Row cursor = conn.cursor() cursor.execute("SELECT * FROM tasks") for row in cursor.fetchall(): status = "✓" if row["completed"] else "✗" print(f"{row['id']}. {row['title']} [{status}]")
def complete_task(task_id): with sqlite3.connect(DB_NAME) as conn: cursor = conn.cursor() cursor.execute("UPDATE tasks SET completed = 1 WHERE id = ?", (task_id,)) if cursor.rowcount == 0: print(f"Task {task_id} not found.") else: print(f"Task {task_id} completed.")
import sqlite3 def run_query(db_path, query, params=()): try: with sqlite3.connect(db_path) as conn: cursor = conn.cursor() cursor.execute(query, params) if query.strip().upper().startswith("SELECT"): return cursor.fetchall() else: return cursor.rowcount # number of affected rows except sqlite3.IntegrityError as e: print(f"Integrity error: {e}") except sqlite3.OperationalError as e: print(f"Operational error: {e}") except Exception as e: print(f"Unexpected error: {e}") return None Here’s a complete, fixed script that incorporates all best practices: sqlite3 tutorial query python fixed
def add_task(title): with sqlite3.connect(DB_NAME) as conn: cursor = conn.cursor() cursor.execute("INSERT INTO tasks (title) VALUES (?)", (title,)) print(f"Task '{title}' added.")
If you’re diving into Python development, you’ll quickly encounter the need for a lightweight, reliable database. Enter SQLite3—a serverless, self-contained database engine that comes bundled with Python. But even with its simplicity, running queries often leads to frustrating pitfalls: incorrect syntax, uncommitted changes, or the dreaded sqlite3.OperationalError . def list_tasks(): with sqlite3
if == " main ": init_db() while True: print("\n1. Add task\n2. List tasks\n3. Complete task\n4. Delete task\n5. Exit") choice = input("Choose: ") if choice == "1": add_task(input("Title: ")) elif choice == "2": list_tasks() elif choice == "3": complete_task(int(input("Task ID: "))) elif choice == "4": delete_task(int(input("Task ID: "))) elif choice == "5": break
conn = sqlite3.connect("data.db") try: cursor = conn.cursor() cursor.execute("INSERT INTO logs (message) VALUES (?)", ("Started process",)) conn.commit() # <-- FIX: Without this, no insert except Exception as e: conn.rollback() print(f"Error: {e}") finally: conn.close() Wrap your queries to avoid crashes. Here’s a robust template: But even with its simplicity, running queries often
cursor.execute("INSERT INTO users (name, age) VALUES (?, ?)", ("Alice",)) # Only one value, two placeholders Match exactly. Use (name, age) for two placeholders. Error 3: sqlite3.IntegrityError: UNIQUE constraint failed Cause: Duplicate value in a column defined as UNIQUE . Fix: Either remove duplicate or use INSERT OR IGNORE or INSERT OR REPLACE .