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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
import sqlite3 # Create and connect with database connection = sqlite3.connect("cars.db") # Create cursor to interact with database cursor = connection.cursor() # Create database table cursor.execute( """CREATE TABLE IF NOT EXISTS car (brand text, model text)""" ) # Insert an entry in the database table cursor.execute( """INSERT INTO car (brand, model) VALUES ('Lamborghini', 'Aventador')""" ) # Commit the changes connection.commit() # Fetch the result from the database table result = cursor.execute( """SELECT * FROM car""" ) # Print the first entry from the table data = result.fetchall() print(data[0]) # Close the database connection connection.close() |
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.
1 |
('Lamborghini', 'Aventador') |
Our database table has only one entry and we printed it.
That’s all for now.
Keep Coding✌✌.