You are currently viewing How To Connect SQLite Database With Python

How To Connect SQLite Database With Python

In this article, we’ll learn how to connect SQLite database with Python.

Connect SQLite Database With Python

The SQLite database driver comes installed with Python so we don’t need any third-party library to access it. Python provides a sqlite3 package to handle connection and interaction with SQLite database.

Create a Python file named db.py and write the following code.

First, we imported the sqlite3 library to help us create and interact with the SQLite database.

Then, using sqlite3.connect("cars.db"), we created the database named cars.db and connected to it. This line created the database because we didn’t have a database named cars.

We don’t require any username and password. This database is very lightweight and stores data into a file, hence, it becomes a great choice for side projects.

Next, we created a cursor using connection.cursor() to help us interact with the database.

After that, we executed two SQL queries using cursor.execute(). The first query creates a table named car with two columns in the database and the second query inserts data in the table.

Then the changes were saved using connection.commit().

Next, we executed another SQL query to select the data from the table and then printed the first result after fetching the data using result.fetchall().

Ultimately, we closed the database connection using connection.close().

When we run this code, we’ll get the result as follows.

Our database table has only one entry and we printed it.


That’s all for now.

Keep Coding✌✌.