Introduction to SQLite

Introduction to SQLite in Python: Imagine you need to store data for your application—user profiles, shop inventory, or game high scores.

Concept Explanation

Imagine you need to store data for your application—user profiles, shop inventory, or game high scores. You could use a text file or JSON, but those get messy and slow as your data grows. You need a Database.

SQLite is a relational database management system (RDBMS) that is "Serverless." Unlike MySQL or PostgreSQL, which require you to install and run a separate server program, SQLite stores everything in a simple .db file on your hard drive.

Python has built-in support for SQLite via the sqlite3 module. It’s perfect for small to medium applications, mobile apps, and temporary data storage.


Syntax or Core Structure

The Connection and Cursor

To talk to SQLite, you need two things:

  1. Connection: The "pipe" between Python and the database file.
  2. Cursor: The "worker" that walks into the database, executes your SQL commands, and brings back the results.
import sqlite3

# 1. Connect (creates the file if it doesn't exist)
conn = sqlite3.connect('my_app.db')

# 2. Create a cursor
cursor = conn.cursor()

# 3. Always close when finished!
# conn.close()

Code Example #1 (Basic)

Creating a table and inserting a row.

import sqlite3

conn = sqlite3.connect('company.db')
cursor = conn.cursor()

# Create a table (if it's not already there)
cursor.execute('''
    CREATE TABLE IF NOT EXISTS employees (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        name TEXT NOT NULL,
        department TEXT,
        salary REAL
    )
''')

# Insert data
cursor.execute("INSERT INTO employees (name, department, salary) VALUES ('Harsh', 'Engineering', 95000)")

# ⚠️ CRITICAL: You must commit changes to save them!
conn.commit()
conn.close()

Code Example #2 (Intermediate)

Fetching data and using Placeholders to prevent SQL Injection.

import sqlite3

conn = sqlite3.connect('company.db')
cursor = conn.cursor()

# WRONG: Using f-strings (Never do this!)
# name = "Alice"
# cursor.execute(f"SELECT * FROM employees WHERE name = '{name}'")

# RIGHT: Using ? placeholders (Safe from hackers)
search_name = "Harsh"
cursor.execute("SELECT * FROM employees WHERE name = ?", (search_name,))

# Fetch one result
employee = cursor.fetchone()
print(f"Found: {employee}")

# Fetch all results
cursor.execute("SELECT * FROM employees")
all_workers = cursor.fetchall()
for row in all_workers:
    print(row)

conn.close()

Real World Example

Inventory Tracker: A script that checks if an item is in stock and updates the quantity.

import sqlite3

def update_inventory(item_id, sold_count):
    conn = sqlite3.connect('store.db')
    cursor = conn.cursor()
    
    # 1. Check current stock
    cursor.execute("SELECT stock FROM products WHERE id = ?", (item_id,))
    current_stock = cursor.fetchone()[0]
    
    if current_stock >= sold_count:
        # 2. Update stock
        new_stock = current_stock - sold_count
        cursor.execute("UPDATE products SET stock = ? WHERE id = ?", (new_stock, item_id))
        conn.commit()
        print(f"Sold! Remaining: {new_stock}")
    else:
        print("Error: Out of stock!")
    
    conn.close()

Common Mistakes

  1. Forgetting to Commit: If you insert or update data but don't call conn.commit(), your changes will vanish the moment you close the program.
  2. SQL Injection: Using string formatting (f"INSERT INTO...") to build queries. Hackers can use this to delete your entire database. Always use ? placeholders.
  3. Not Closing Connections: Too many open connections can slow down your computer or lock the database file. Use a with block: with sqlite3.connect(...) as conn:.

Best Practices

  • Use the 'with' statement: with sqlite3.connect('db.db') as conn: automatically commits or rolls back changes if an error occurs.
  • Keep Logic Separate: Create a separate Python file or class (like a "Database Manager") to handle all your SQL code.
  • Indexing: For large databases, add INDEX to columns you search frequently to make queries 100x faster.

Practice Exercises

  1. The Student Database: Create a table for students with Name, Grade, and Subject. Insert 3 students and print their names.
  2. The Salary Bump: Write a script that finds all employees in a specific department and increases their salary by 10%.
  3. The Deleter: Create a function that takes a student ID and deletes them from the database. Verify they are gone using a SELECT query.