Insert data into SQLite table using Python For Loop

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.

Comments & Discussion

Facing issues? Have questions? Post them here! We're happy to help!