Python Data Persistence (SQLite)

Python Data Persistence (SQLite)

SQLite is a lightweight, disk-based database that doesn't require a separate server process. Python has built-in support for SQLite through the sqlite3 module.

Creating a Database

You can create a new SQLite database and perform CRUD (Create, Read, Update, Delete) operations:

      
        import sqlite3

        # Connect to the database (or create it)
        conn = sqlite3.connect('example.db')
        cursor = conn.cursor()

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

        # Insert data
        cursor.execute("INSERT INTO users (name, age) VALUES ('Alice', 30)")
        conn.commit()

        # Query data
        cursor.execute("SELECT * FROM users")
        rows = cursor.fetchall()
        for row in rows:
            print(row)

        conn.close()
      
    

Activity

Try It Yourself!

Create a database that stores books, including the title, author, and publication year. Insert a few records and retrieve them.

Quick Quiz

Quick Quiz

  1. What is SQLite?
  2. Which Python module is used to interact with SQLite databases?

Answers: SQLite is a lightweight, disk-based database