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.

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap