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
Approach:
- 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:
Python3
import csv
import sqlite3
try:
with open('student_info.csv', 'r') as fin:
dr = csv.DictReader(fin)
student_info = [(i['NAME'], i['AGE']) for i in dr]
print(student_info)
sqliteConnection = sqlite3.connect('sql.db')
cursor = sqliteConnection.cursor()
cursor.execute('create table student(name varchar2(10), age int);')
cursor.executemany(
"insert into student (name, age) VALUES (?, ?);", student_info)
cursor.execute('select * from student;')
result = cursor.fetchall()
print(result)
sqliteConnection.commit()
cursor.close()
except sqlite3.Error as error:
print('Error occurred - ', error)
finally:
if sqliteConnection:
sqliteConnection.close()
print('SQLite Connection closed')
|
Output:

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
06 Oct, 2022
Like Article
Save Article