Python's SQLite module provides multiple methods to insert data into database tables safely and efficiently. After creating a table, inserting data is the next fundamental operation for building functional database applications.
Basic Insert Operations
The most straightforward approach uses the execute() method with INSERT SQL statements:
import sqlite3
conn = sqlite3.connect('example.db')
cursor = conn.cursor()
# Insert single record
cursor.execute('''
INSERT INTO users (name, email, age)
VALUES ('John Doe', '[email protected]', 25)
''')
conn.commit()
conn.close()
Parameterized Queries (Recommended)
Always use parameterized queries to prevent SQL injection attacks and handle special characters properly:
# Using question mark placeholders
user_data = ('Jane Smith', '[email protected]', 30)
cursor.execute('INSERT INTO users (name, email, age) VALUES (?, ?, ?)', user_data)
# Using named placeholders
cursor.execute('''
INSERT INTO users (name, email, age)
VALUES (:name, :email, :age)
''', {'name': 'Bob Wilson', 'email': '[email protected]', 'age': 35})
Bulk Insert Operations
For inserting multiple records efficiently, use executemany():
users_list = [
('Alice Brown', '[email protected]', 28),
('Charlie Davis', '[email protected]', 32),
('Diana Miller', '[email protected]', 27)
]
cursor.executemany('INSERT INTO users (name, email, age) VALUES (?, ?, ?)', users_list)
Error Handling and Best Practices
Implement proper error handling for constraints violations:
try:
cursor.execute('INSERT INTO users (name, email, age) VALUES (?, ?, ?)',
('Test User', '[email protected]', 25))
conn.commit()
except sqlite3.IntegrityError as e:
print(f"Insert failed: {e}")
conn.rollback()
Key Points
- Always use parameterized queries with
?or named placeholders to prevent SQL injection - Call
conn.commit()to save changes permanently - Use
executemany()for bulk operations to improve performance - Implement try-except blocks to handle constraint violations gracefully
- Consider using context managers (
withstatements) for automatic connection management
These techniques ensure secure, efficient data insertion while maintaining database integrity and application reliability.