The Wayback Machine - https://web.archive.org/web/20240605010722/https://www.geeksforgeeks.org/how-to-import-a-csv-file-into-a-sqlite-database-table-using-python/
Open In App

How to Import a CSV file into a SQLite database Table using Python?

Last Updated : 28 Oct, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we are going to discuss how to import a CSV file content into an SQLite database table using Python.

Approach:

  • At first, we import csv module (to work with csv file) and sqlite3 module (to populate the database table).
  • Then we connect to our geeks database using the sqlite3.connect() method.
  • At this point, we create a cursor object to handle queries on the database table.
  • We first create our person table and create a csv file with the contents inside which we will be inserting into our table.
  • We open the above-created csv file using the open() function.
  • We extract all the contents of the csv file into our contents variable through csv.reader() method.
  • Then we insert our row-wise contents of csv file into our database through executemany() method which will replace (?,?) with the next two comma-separated data of the csv file and insert it as a record into the person table.
  • Finally, we verify that the data of the csv file has been successfully inserted into our table with the SELECT statement and commit the changes and close the database connection.

Below is the implementation.

For the purpose of implementation, we will be creating a person table in our geeks.db database. We are going to insert the content of the person_records.csv in our person table. Below is the CSV file we are going to use:

Below is the complete program based on the above approach:

Python3




# Import required modules
import csv
import sqlite3
 
# Connecting to the geeks database
connection = sqlite3.connect('g4g.db')
 
# Creating a cursor object to execute
# SQL queries on a database table
cursor = connection.cursor()
 
# Table Definition
create_table = '''CREATE TABLE person(
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                name TEXT NOT NULL,
                age INTEGER NOT NULL);
                '''
 
# Creating the table into our
# database
cursor.execute(create_table)
 
# Opening the person-records.csv file
file = open('person-records.csv')
 
# Reading the contents of the
# person-records.csv file
contents = csv.reader(file)
 
# SQL query to insert data into the
# person table
insert_records = "INSERT INTO person (name, age) VALUES(?, ?)"
 
# Importing the contents of the file
# into our person table
cursor.executemany(insert_records, contents)
 
# SQL query to retrieve all data from
# the person table To verify that the
# data of the csv file has been successfully
# inserted into the table
select_all = "SELECT * FROM person"
rows = cursor.execute(select_all).fetchall()
 
# Output to the console screen
for r in rows:
    print(r)
 
# Committing the changes
connection.commit()
 
# closing the database connection
connection.close()


Output:

SQLite:



Previous Article
Next Article

Similar Reads

How to import CSV file in SQLite database using Python ?
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. [caption width="800"]Contents of the CSV file[/caption] Approach: Importing necessary modulesRead data from CSV file Di
2 min read
Creating a sqlite database from CSV with Python
Prerequisites: PandasSQLite SQLite is a software library that implements a lightweight relational database management system. It does not require a server to operate unlike other RDBMS such as PostgreSQL, MySQL, Oracle, etc. and applications directly interact with a SQLite database. SQLite is often used for small applications, particularly in embed
2 min read
Create a GUI to convert CSV file into excel file using Python
Prerequisites: Python GUI – tkinter, Read csv using pandas CSV file is a Comma Separated Value file that uses a comma to separate values. It is basically used for exchanging data between different applications. In this, individual rows are separated by a newline. Fields of data in each row are delimited with a comma. Modules Needed Pandas: Python i
3 min read
Python - Import CSV into PostgreSQL
In this article, we will see how to import CSV files into PostgreSQL using the Python package psycopg2. First, we import the psycopg2 package and establish a connection to a PostgreSQL database using the pyscopg2.connect() method. before importing a CSV file we need to create a table. In the example below, we created a table by executing the "creat
2 min read
Convert HTML table into CSV file in python
CSV file is a Comma Separated Value file that uses a comma to separate values. CSV file is a useful thing in today's world when we are talking about machine learning, data handling, and data visualization. In this article, we will discuss how to convert an HTML table into a CSV file. Converting HTML Table into CSV file in Python Example: Suppose HT
2 min read
How to create multiple CSV files from existing CSV file using Pandas ?
In this article, we will learn how to create multiple CSV files from existing CSV file using Pandas. When we enter our code into production, we will need to deal with editing our data files. Due to the large size of the data file, we will encounter more problems, so we divided this file into some small files based on some criteria like splitting in
3 min read
Different ways to import csv file in Pandas
CSV files are the "comma separated values", these values are separated by commas, this file can be viewed as an Excel file. In Python, Pandas is the most important library coming to data science. We need to deal with huge datasets while analyzing the data, which usually can be in CSV file format. Let's see the different ways to import csv files in
3 min read
Store Google Sheets data into SQLite Database using Python
In this article, we are going to store google sheets data into a database using python. The first step is to enable the API and to create the credentials, so let's get stared. Enabling the APIs and creating the credentialsGo to Marketplace in Cloud Console.Click on ENABLE APIS AND SERVICESThen Search for Google Drive API and enable itThen go to the
5 min read
How to import an excel file into Python using Pandas?
It is not always possible to get the dataset in CSV format. So, Pandas provides us the functions to convert datasets in other formats to the Data frame. An excel file has a '.xlsx' format. Before we get started, we need to install a few libraries. pip install pandas pip install xlrd For importing an Excel file into Python using Pandas we have to us
2 min read
Scrape and Save Table Data in CSV file using Selenium in Python
Selenium WebDriver is an open-source API that allows you to interact with a browser in the same way a real user would and its scripts are written in various languages i.e. Python, Java, C#, etc. Here we will be working with python to scrape data from tables on the web and store it as a CSV file. As Google Chrome is the most popular browser, to make
3 min read
Article Tags :
Practice Tags :