SQLite in Python

Elshad Karimov
1 min readJul 6, 2024
Photo by Chris Ried on Unsplash

SQLite is a lightweight, disk-based database that doesn’t require a separate server process. Python’s built-in sqlite3module makes it easy to work with SQLite databases.

Creating a Database

First, import the sqlite3 module and connect to a database (it will be created if it doesn’t exist):

import sqlite3

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

Creating a Table

Create a table by executing SQL commands:

c = conn.cursor()
c.execute('''CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)''')
conn.commit()

Inserting Data

Insert data into the table:

c.execute("INSERT INTO users (name, age) VALUES ('Alice', 30)")
conn.commit()

Querying Data

Retrieve data using a SELECT statement:

c.execute("SELECT * FROM users")
print(c.fetchall()) # [(1, 'Alice', 30)]

Closing the Connection

Always close the connection when done:

conn.close()

SQLite with Python is perfect for small to medium-sized applications needing a simple, fast, and reliable database.

If you found them helpful:

  • Show some love with a 50-clap
  • Drop a comment.
  • Share your favorite part!

Discover more in my online courses at AppMillers 🚀

Connect on LinkedIn: Elshad Karimov

Follow on X (Twitter): Elshad Karimov

Subscribe to our Newsletter for recent Technological advancements: Newsletter by Elshad Karimov

--

--

Elshad Karimov

Software Engineer, Udemy Instructor and Book Author, Founder at AppMillers