backup_database("mydatabase_backup.db")
In this tutorial, we'll explore the basics of SQLite3 and learn how to query a database using Python. We'll create a sample database, insert data, and then perform various queries to retrieve and manipulate the data.
def execute_query_with_error_handling(query, params=None):
try:
if params:
cursor.execute(query, params)
else:
cursor.execute(query)
conn.commit()
return cursor.fetchall() if query.strip().upper().startswith('SELECT') else None
except sqlite3.IntegrityError as e:
print(f"Integrity Error: e")
return None
except sqlite3.OperationalError as e:
print(f"Operational Error: e")
return None
except Exception as e:
print(f"General Error: e")
return None
Cause: Duplicate value in a column defined as UNIQUE.
Fix: Either remove duplicate or use INSERT OR IGNORE or INSERT OR REPLACE. sqlite3 tutorial query python fixed
cursor.execute("INSERT OR IGNORE INTO users (name, email) VALUES (?, ?)", ("Bob", "bob@example.com"))
SQLite3 comes built-in with Python. No additional installation needed!
import sqlite3
import os
cursor.execute('''
CREATE TABLE IF NOT EXISTS posts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER,
title TEXT NOT NULL,
content TEXT,
FOREIGN KEY (user_id) REFERENCES users (id)
)
''') backup_database("mydatabase_backup
conn.commit()
print("Tables created successfully!")
def get_users_by_age(min_age, limit=10):
conn = sqlite3.connect('my_database.db')
cursor = conn.cursor()
cursor.execute(
"SELECT * FROM users WHERE age > ? LIMIT ?",
(min_age, limit)
)
rows = cursor.fetchall()
conn.close()
return rows
Retrieve only the name and email columns from the users table: SQLite3 comes built-in with Python
cursor.execute('SELECT name, email FROM users')
rows = cursor.fetchall()
for row in rows:
print(row)
Output:
('John Doe', 'john@example.com')
('Jane Doe', 'jane@example.com')
('Bob Smith', 'bob@example.com')
Enjoy in website ? Visit our social media :)
This will close in 20 seconds