Basic Usage of SQLite in a Python Application: A Step-by-Step Guide

In this article, we’ll explore the basic usage of SQLite in a Python application.

Posted on

SQLite is a lightweight, serverless, and self-contained relational database management system (RDBMS). It’s a great choice for small to medium-sized projects and embedded systems. In this article, we’ll explore the basic usage of SQLite in a Python application. We’ll cover the steps for connecting to SQLite, performing common database operations, and handling data using the built-in sqlite3 library.

Prerequisites

Before we start, make sure you have Python installed on your system. You can download Python from the official Python website.

Step 1: Connecting to SQLite

To use SQLite in a Python application, you don’t need to install a separate database server. SQLite databases are just files, making it easy to get started. Here’s a basic example of how to connect to an SQLite database:

import sqlite3

# Create or connect to a SQLite database
db_connection = sqlite3.connect('mydatabase.db')

# Create a cursor object to interact with the database
cursor = db_connection.cursor()

# Perform database operations here

# Close the database connection when done
db_connection.close()

In the code above, we connect to an SQLite database file named 'mydatabase.db'. If the file doesn’t exist, it will be created automatically. You can replace 'mydatabase.db' with the desired name for your SQLite database.

Step 2: Performing Database Operations

Once connected, you can perform various database operations, such as creating tables, inserting data, querying data, updating records, and deleting records. Here are some examples:

Creating a Table

# Create a table
cursor.execute('''
    CREATE TABLE IF NOT EXISTS users (
        id INTEGER PRIMARY KEY,
        username TEXT NOT NULL,
        email TEXT NOT NULL
    )
''')

Inserting Data

# Insert data into the table
cursor.execute("INSERT INTO users (username, email) VALUES (?, ?)", ("john_doe", "[email protected]"))

Querying Data

# Query data from the table
cursor.execute("SELECT * FROM users")
rows = cursor.fetchall()

for row in rows:
    print(f"ID: {row[0]}, Username: {row[1]}, Email: {row[2]}")

Updating Data

# Update data in the table
cursor.execute("UPDATE users SET email = ? WHERE username = ?", ("[email protected]", "john_doe"))

Deleting Data

# Delete data from the table
cursor.execute("DELETE FROM users WHERE username = ?", ("john_doe",))

Step 3: Error Handling

It’s essential to handle errors gracefully when working with databases. In the examples above, sqlite3 provides error handling for many common database errors. You can catch and handle exceptions as needed in your application.

Conclusion

In this article, we’ve covered the basic usage of SQLite in a Python application using the built-in sqlite3 library. You’ve learned how to connect to an SQLite database, create tables, insert data, query data, update records, and delete records. SQLite is a simple yet powerful choice for projects where you need a lightweight, self-contained database. These fundamental skills will serve as a solid foundation for building more complex database-driven applications with SQLite and Python.