Open In App
Related Articles

How to import CSV file in SQLite database using Python ?

Like Article
Save Article
Report issue

In this article, we’ll learn how to import data from a CSV file and store it in a table in the SQLite database using Python. You can download the CSV file from here which contains sample data on the name and age of a few students.

Contents of the CSV file


  • Importing necessary modules
  • Read data from CSV file DictReader()
  • Establish a connection with the database.
sqliteConnection = sqlite3.connect('sql.db')
cursor = sqliteConnection.cursor()
  • Create the student table and execute the query using execute() method.
  • Inserting data into the table
cursor.executemany("insert into student (name, age) VALUES (?, ?);", student_info)
  • Read data from the table
  • And close the database.

Below is the implementation:


import csv
import sqlite3
    # Import csv and extract data
    with open('student_info.csv', 'r') as fin:
        dr = csv.DictReader(fin)
        student_info = [(i['NAME'], i['AGE']) for i in dr]
    # Connect to SQLite
    sqliteConnection = sqlite3.connect('sql.db')
    cursor = sqliteConnection.cursor()
    # Create student table
    cursor.execute('create table student(name varchar2(10), age int);')
    # Insert data into table
        "insert into student (name, age) VALUES (?, ?);", student_info)
    # Show student table
    cursor.execute('select * from student;')
    # View result
    result = cursor.fetchall()
    # Commit work and close connection
except sqlite3.Error as error:
    print('Error occurred - ', error)
    if sqliteConnection:
        print('SQLite Connection closed')



Don't miss your chance to ride the wave of the data revolution! Every industry is scaling new heights by tapping into the power of data. Sharpen your skills and become a part of the hottest trend in the 21st century.

Dive into the future of technology - explore the Complete Machine Learning and Data Science Program by GeeksforGeeks and stay ahead of the curve.

Last Updated : 06 Oct, 2022
Like Article
Save Article
Share your thoughts in the comments
Similar Reads
Complete Tutorials