In this example, we take a look at how to insert data into an SQLite database table using a for loop in Python.
import sqlite3
conn = sqlite3.connect('mydb.db')
cursor = conn.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS employees (
emp_id INTEGER PRIMARY KEY,
emp_name TEXT,
emp_dept TEXT
)
''')
insert_emp_data = [
('Mike', 'IT'),
('Alan', 'Finance'),
('Jane', 'HR')
]
for data in insert_emp_data:
cursor.execute('INSERT INTO employees (emp_name, emp_dept) VALUES (?, ?)', data)
conn.commit()
cursor.close()
conn.close()
Make sure to commit and close the connection and the cursor.
Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!