🐍

Getting Started with SQLite in Python

May 25, 2025

SQLite Overview and Setup

Introduction to SQLite

  • SQLite is useful for database functionality without requiring a full-fledged database system like MySQL or Postgres.
  • Ideal for small to medium-sized applications, testing, and prototyping.
  • Part of the Python standard library, hence requires no installation.
  • Database can be a simple file or an in-memory database.

Assumptions

  • Assumes basic knowledge of SQL for the tutorial.

Sample Code

  • Uses sample code from an object-oriented series, specifically focusing on an Employee class.
  • The main file for SQLite demonstration is sqlite_demo.py.

Working with SQLite in Python

Setting Up Connection

  • Import SQLite3 with import sqlite3.
  • Create a connection object using sqlite3.connect(), which can connect to a file or create an in-memory database.
  • Example: conn = sqlite3.connect('employee.db') creates a file-based database, whereas conn = sqlite3.connect(':memory:') creates an in-memory database.

Creating a Cursor

  • Create a cursor using cursor = conn.cursor() to execute SQL commands.

Creating a Table

  • Use CREATE TABLE SQL command to create tables.
  • Example table schema: id, first_name, last_name, and pay.
  • Data types: TEXT, INTEGER, etc.

Inserting Data

  • Use INSERT INTO SQL command to add data.
  • Example: cursor.execute("INSERT INTO employees VALUES (?, ?, ?)", (first_name, last_name, pay)).
  • Commit changes with conn.commit().

Querying Data

  • Use SELECT SQL command to retrieve data.
  • Example: cursor.execute("SELECT * FROM employees WHERE last=?", (last_name,)).
  • Fetch results using fetchone(), fetchmany(size), or fetchall().*

Using Placeholders

  • Prevent SQL injection by using placeholders (? or :variable) in queries.
  • Use tuples or dictionaries to pass values.

Advanced Usage

Using Context Managers

  • Use with conn: to manage transactions, automatically committing or rolling back.

Example Functions

  • Create functions for common operations: insert_employee, get_employee_by_name, update_pay, remove_employee.

Prototyping with In-Memory Database

  • Use in-memory databases for testing, which start fresh on every run.

Closing the Connection

  • Always close the connection with conn.close().

Additional Resources

Further Learning

  • Explore bulk inserts and advanced SQLite features.
  • Consider using SQLite with SQLAlchemy for ORM capabilities.

Community Support

  • Engage with the community for questions and further assistance.

Supporting the Creator

  • Options include liking, sharing, and supporting through Patreon.

Conclusion

  • SQLite offers a lightweight, easy-to-use solution for database management in small to medium applications.