BeginnerCoder
intermediate#python#sqlite#databases

Working with Databases in Python using SQLite

This article was AI-drafted and has not been reviewed yet. Spotted a mistake? Tell us.

Learn how to use the SQLite database in Python to store and retrieve data, including creating tables, inserting data, and querying data.

Introduction to SQLite

SQLite is a lightweight disk-based database library that doesn’t require a separate server process.

Connecting to the Database

You can connect to the database using the following command:

import sqlite3
# connect to the database
conn = sqlite3.connect('example.db')
# create a cursor object
cursor = conn.cursor()

Creating Tables

You can create tables in the database using the CREATE TABLE statement.

# create a table
cursor.execute('CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)')

Inserting Data

You can insert data into the tables using the INSERT INTO statement.

# insert data
cursor.execute('INSERT INTO users (name, age) VALUES (?, ?)', ('John Doe', 30))
# commit the changes
conn.commit()
Keep going with python

Ready for more? Optional paid resources that pick up where this lesson leaves off.

Some links on this page are affiliate links: we may earn a commission at no extra cost to you. As an Amazon Associate I earn from qualifying purchases.