How to Bulk Insert Rows into SQLite in Python
Insert many rows into an SQLite table in one call with cursor.executemany, then verify them with a SELECT query.
Python code
27 linesimport sqlite3
# Create an in-memory database and a table
conn = sqlite3.connect(":memory:")
cursor = conn.cursor()
cursor.execute("CREATE TABLE products (name TEXT, price REAL, quantity INTEGER)")
# Data to insert in bulk
products = [
("Laptop", 999.99, 5),
("Mouse", 19.99, 50),
("Keyboard", 49.99, 30),
("Monitor", 199.99, 15),
("USB Cable", 9.99, 100)
]
# Bulk insert with executemany
cursor.executemany("INSERT INTO products (name, price, quantity) VALUES (?, ?, ?)", products)
conn.commit()
# Verify the inserted rows
cursor.execute("SELECT * FROM products")
rows = cursor.fetchall()
for row in rows:
print(row)
conn.close()
Output
('Laptop', 999.99, 5)
('Mouse', 19.99, 50)
('Keyboard', 49.99, 30)
('Monitor', 199.99, 15)
('USB Cable', 9.99, 100)
How it works
The executemany method takes an SQL template with ? placeholders and a list of tuples, executing the same INSERT statement once per tuple. Because the connection is in-memory, it's created fresh every run and doesn't persist after close(). The commit() call ensures the changes are written; without it, the transaction might be rolled back when the connection closes. Finally, fetchall() returns all selected rows as a list of tuples that you can iterate over to print.
Common mistakes
- Forgetting to call conn.commit() after executemany, losing changes on close.
- Passing a generator instead of a list or iterable that can be consumed only once.
Variations
- Use sqlite3.connect('mydb.db') to write to a file instead of in-memory.
- Use executemany with parameterized queries for other SQL like UPDATE or DELETE.
Real-world use cases
- Seeding a development database with thousands of sample records at startup.
- Bulk importing CSV rows into a local SQLite cache for analysis or reporting.
- Persisting user-generated data like form submissions in batches for performance.
Sponsored
More from Files & data
- Append a Line to a Log File in Python easy
- Audit File Permissions Across a Project in Python easy
- Automatically Detect Corrupted Files Using SHA-256 Checksums in Python easy
- Automatically Highlight Data Validation Errors Inside Excel Files in Python easy
- Build a Command-Line To-Do List Application with Data Persistence in Python easy
- Build a File Index by Relative Path Hash Map in Python easy
Keep learning
Related tutorials and quizzes for this topic.