How To Use an SQLite Database With Python [Step-By-Step]

Claudio Sabato
8 min readMar 18

In this Python tutorial, we will learn how to connect to an SQLite database and how to perform CRUD (Create Read Update Delete) operations using Python.

How can you use a database in Python? And specifically an SQLite database?

To interact with an SQLite database in Python you have to connect to the database, create a cursor and use the execute() function on the cursor. This allows you to execute all the CRUD operations you need. Remember to commit() your changes and to close() your database connection once you are done with it.

We will go through each one of the steps mentioned above so you can use this knowledge in your Python applications.

Let’s learn how to use SQLite with Python!

How to Connect to an SQLite3 Database Using Python

The first step to connect to an SQLite database in Python is to import the module sqlite3 which is part of Python since version 2.5 so you do not need to install it if you are using Python 3 (and you should).

This module provides an interface for interacting with SQLite databases that is compliant with the Database API Specification 2.0.

import sqlite3

To read data from an SQLite database you have to connect to it using the connect() function of the sqlite3 module. You have to pass the filename of the SQLite database to the connect() function.

The filename of the database we will use in this example is flight_booking.db.

So far we haven’t created a database file, so what happens if we execute the following Python statement?

conn = sqlite3.connect('flight_booking.db')

When we execute the code to connect to the SQLite database, Python automatically creates the database file in the local directory if it doesn’t already exist.

From the shell below you can see that an empty SQLite database file called flight_booking.db has been created.

(python-env) # ls -ltr flight_booking.db 
-rw-r--r-- 1 codefather codefather 0 Mar 18 09:52 flight_booking.db
Claudio Sabato

I’m a Software Engineer and Programming Coach. I want to help you in your journey to become a Super Developer!