Libraries and Frameworks

SQLite with Python: A beginner-friendly tutorial

Learn how to use Python's sqlite3 module in this beginner-friendly tutorial. Create databases and tables, insert, update, select, and delete data with complete, ready-to-run examples.

joao • 05 Nov 2026 • 9 min read • 141 • 0
SQLite with Python: A beginner-friendly tutorial | Usando Python
Publicidade

If you are new to Python and have never worked with databases before, do not worry. This tutorial walks you through SQLite step by step, using plain language and small, complete examples you can run yourself. By the end, you will know how to create a database, add data, read it, update it, and delete it, all from Python.

What Is SQLite?

SQLite is a small, fast, and very reliable SQL database engine written in C. Unlike other database systems, it does not need a separate server. There is nothing to install or configure. Your entire database, including all tables, indexes, triggers, and views, lives in a single file on your disk.

This has some practical advantages:

  • It reads and writes directly to ordinary files.

  • The same database file works across 32-bit and 64-bit systems, and across different processor architectures.

  • It is in the public domain, so you can use it freely for commercial or private projects.

  • It is a great choice for learning, for prototypes, and for small applications. If your project grows, you can migrate to a larger database such as PostgreSQL or Oracle later.

What Is the sqlite3 Module?

Python ships with a built-in module called sqlite3. You do not need to install anything with pip. This module was developed by Gerhard Häring and follows the DB-API 2.0 specification (PEP 249), which means it behaves in a standard way that is consistent with other Python database modules.

Because it is part of the standard library, you can start using it right away:

import sqlite3

Step 1: Connecting to a Database

The first thing you do with any database is connect to it.

import sqlite3

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

Two things can happen here:

  • If the file example.db does not exist, SQLite creates it automatically.

  • If the file already exists, the command simply opens a connection to it.

If you prefer to keep everything in memory and avoid creating a file, use the special name :memory::

conn = sqlite3.connect(':memory:')

An in-memory database disappears when the program ends. This is useful for experiments and tests.

Step 2: A Reusable Connection Function

As your project grows, you will connect to the database in several places. It is a good idea to write a small function once and reuse it. Create a file called create_con.py:

import sqlite3
from sqlite3 import Error

def create_connection(db_file):
    """Creates a connection to a SQLite database."""
    conn = None
    try:
        conn = sqlite3.connect(db_file)
        print(sqlite3.version)
        return conn
    except Error as e:
        print(f"Error: {e}")
        return None

if __name__ == '__main__':
    create_connection('sqlite.db')

This function tries to connect to the database you pass as an argument. If it succeeds, it prints the SQLite version and returns the connection. If something goes wrong, it prints the error and returns None.

Step 3: Planning the Tables

Before writing code, let us decide what we want to store. Our example is a small library with two tables:

authors stores authors:

  • id: a unique primary key that identifies an author

  • name: the author's name

  • born_date: the author's birth date

books stores books:

  • id: a unique primary key that identifies a book

  • title: the book title

  • author_id: the ID of the author (a foreign key pointing to authors.id)

Here is the relationship in a simple diagram:

┌─────────────┐         ┌─────────────┐
│   authors   │         │    books    │
├─────────────┤         ├─────────────┤
│ id (PK)     │◄────────│ id (PK)     │
│ name        │         │ title       │
│ born_date   │         │ author_id   │
└─────────────┘         └─────────────┘

This is a one-to-many relationship. One author can have many books, but each book belongs to only one author.

Step 4: Creating the Tables

Now let us create the tables with SQL. The SQL statements are:

-- authors table
CREATE TABLE IF NOT EXISTS authors (
    id integer PRIMARY KEY,
    name text NOT NULL,
    born_date text
);

-- books table
CREATE TABLE IF NOT EXISTS books (
    id integer PRIMARY KEY,
    title text NOT NULL,
    author_id integer NOT NULL,
    FOREIGN KEY (author_id) REFERENCES authors (id)
);

The IF NOT EXISTS part means the command will not fail if the table is already there.

Put this into a file called create_tables.py:

import sqlite3
from sqlite3 import Error
from create_con import create_connection

DB = 'sqlite.db'
conn = create_connection(DB)

def create_table(conn, create_table_sql):
    try:
        c = conn.cursor()
        c.execute(create_table_sql)
    except Error as e:
        print(e)

sql_create_authors_table = """
CREATE TABLE IF NOT EXISTS authors(
    id integer PRIMARY KEY,
    name text NOT NULL,
    born_date text
);
"""

sql_create_books_table = """
CREATE TABLE IF NOT EXISTS books(
    id integer PRIMARY KEY,
    title text NOT NULL,
    author_id integer NOT NULL,
    FOREIGN KEY (author_id) REFERENCES authors (id)
);
"""

if conn is not None:
    create_table(conn, sql_create_authors_table)
    create_table(conn, sql_create_books_table)
else:
    print('Error! Cannot create the database!')

A quick note on the cursor you see here: a cursor is an object that sends SQL commands to the database and lets you read the results. You can think of it as a pointer that walks through the rows of your query results.

Step 5: Inserting Data

To add data, we use the INSERT statement. The important detail here is the use of placeholders (? or named placeholders like :title). Placeholders protect your code from SQL injection and make the queries cleaner.

import sqlite3
from sqlite3 import Error
from create_con import create_connection

DB = 'sqlite.db'
conn = create_connection(DB)
cur = conn.cursor()

def create_author(conn, author):
    sql = """INSERT INTO authors(name,born_date)
        VALUES(?,?)"""
    try:
        with conn:
            cur.execute(sql, author)
    except sqlite3.IntegrityError:
        print("couldn't add author")
    return cur.lastrowid

def create_books(conn, books):
    sql = """INSERT INTO books(title,author_id)
        VALUES(:title,:author_id)"""
    try:
        with conn:
            cur.executemany(sql, books)
    except sqlite3.IntegrityError:
        print("couldn't add books")
    return cur.lastrowid

with conn:
    author = ('Aldous Huxley', '1894-07-26')
    author_id = create_author(conn, author)

    books = [
        ('Brave New World', author_id),
        ('The Perennial Philosophy', author_id),
        ('The Doors of Perception', author_id),
        ('The Art of Seeing', author_id),
        ('Update Field', 5)
    ]

    create_books(conn, books)

Let us go through the key ideas:

  • create_author inserts one author. create_books inserts a list of books using executemany, which is efficient for many rows at once.

  • Both functions return cur.lastrowid, the ID that was generated for the last inserted row. We use it as author_id when inserting the books.

  • The with conn: block is a context manager. If everything succeeds, the transaction is committed automatically. If an exception happens, the transaction is rolled back. This is a safe and clean way to work with transactions.

Step 6: Updating Data

To change existing rows, use the UPDATE statement.

import sqlite3
from sqlite3 import Error
from create_con import create_connection

DB = 'sqlite.db'
conn = create_connection(DB)

def update_book(conn, book):
    sql = """UPDATE books SET
                title = ?,
                author_id = ?
            WHERE id = ?"""
    cur = conn.cursor()
    cur.execute(sql, book)
    conn.commit()

book = ('Ape and Essence', 1, 5)

with conn:
    update_book(conn, book)

The tuple ('Ape and Essence', 1, 5) fills the three placeholders in order: the new title, the new author ID, and the ID of the book we want to update. Always be careful with the WHERE clause. Without it, every row in the table would be updated.

Step 7: Selecting Data

The SELECT statement reads data from the database. It is the command you will use most often.

import sqlite3
from sqlite3 import Error
from create_con import create_connection

DB = 'sqlite.db'
conn = create_connection(DB)
cur = conn.cursor()

def select_book(conn, id):
    cur.execute('SELECT * from books WHERE id=:id', {'id': id})
    row = cur.fetchone()
    print(row)

def select_books(conn):
    cur.execute('SELECT * from books')
    rows = cur.fetchall()
    for row in rows:
        print(row)

def select_author(conn, id):
    cur.execute('SELECT * from authors WHERE id=?', (id,))
    row = cur.fetchone()
    print(row)

def select_authors(conn):
    cur.execute('SELECT * from authors')
    rows = cur.fetchall()
    for row in rows:
        print(row)

with conn:
    print('SELECT * from books;')
    select_books(conn)
    print('SELECT * from authors;')
    select_authors(conn)
    print('SELECT * from books where id = 3;')
    select_book(conn, 3)
    print('SELECT * from authors where id = 1;')
    select_author(conn, 1)

Here are the four functions and what they do:

  • select_book returns a single book by ID using fetchone.

  • select_books returns all books using fetchall and prints each one.

  • select_author returns a single author by ID.

  • select_authors returns all authors.

Note the two styles of placeholders shown here. ? is a positional placeholder, and :id is a named placeholder that you pass as a dictionary. Both work well. When passing a single value with ?, remember the trailing comma in (id,) so Python treats it as a tuple.

Step 8: Deleting Data

The DELETE statement removes rows from a table.

import sqlite3
from sqlite3 import Error
from create_con import create_connection

DB = 'sqlite.db'
conn = create_connection(DB)

def delete_book(conn, id):
    sql = f'DELETE FROM books where id = {id}'
    cur = conn.cursor()
    cur.execute(sql)
    conn.commit()

def delete_all_authors(conn):
    sql = 'DELETE FROM authors'
    cur = conn.cursor()
    cur.execute(sql)
    conn.commit()

with conn:
    delete_book(conn, 5)
    delete_all_authors(conn)

Two warnings:

  • delete_all_authors removes every row in the authors table. There is no undo. Run it only when you really mean it.

  • The delete_book example uses an f-string to build the SQL. This works for a number, but in real code prefer placeholders, as shown earlier, because placeholders protect you from SQL injection.

Step 9: Shortcut Methods

Python's sqlite3 module also offers shortcut methods directly on the connection object: execute, executemany, and executescript. These create the cursor for you and return it, so your code becomes shorter and easier to read.

import sqlite3

pokemons = [
    ("Bulbasaur", "Grass"),
    ("Charmander", "Fire"),
    ("Squirtle", "Water"),
    ("Pikachu", "Electric")
]

con = sqlite3.connect(":memory:")

con.execute("create table pokemon(name, type)")

con.executemany("insert into pokemon(name, type) values (?, ?)", pokemons)

for row in con.execute("select name, type from pokemon"):
    print(row)

con.close()

In this example we:

  1. Connect to an in-memory database.

  2. Create a pokemon table.

  3. Insert several rows at once with executemany.

  4. Iterate over the results of a select directly.

Notice that we never created a cursor explicitly. The shortcut methods handled that for us. This is the style many experienced Python developers prefer for small scripts.

A Few Practical Tips

  • Always use placeholders (? or :name) instead of string formatting when inserting values. This keeps your code safe.

  • Use with conn: around write operations. It commits on success and rolls back on error, which saves you from half-finished changes.

  • Close connections when your program is done, especially with file-based databases. You can call conn.close().

  • Keep your database file out of version control if it contains real data. Add it to .gitignore.

  • Start with :memory: when experimenting. It keeps your disk clean and resets every run.

Summary

You have now seen the full cycle of working with SQLite from Python:

  1. Connect to a database file or to :memory:.

  2. Create tables with CREATE TABLE.

  3. Insert rows with INSERT and placeholders.

  4. Update rows with UPDATE.

  5. Read rows with SELECT and fetchone or fetchall.

  6. Delete rows with DELETE.

  7. Write shorter code with the connection shortcut methods.

Everything here uses only the standard library, so there is nothing to install. Try each example in a small script, look at the printed output, and experiment by changing values. That is the fastest way to become comfortable with the sqlite3 module.

🎯 Test your knowledge

Take the interactive quiz on this topic and check your score.

Take the Quiz
Publicidade
Você ainda não está logado, por favor faça login ou registre-se para comentar
    0 pessoas participaram | 0 comentários
    Ainda não há comentários, fique à vontade para conversar!