Courses / Computer Science XII (HSSC-II) – FBISE Complete SLO-Based Course

3.7 Connecting Python to a Database (SQLite)

Unit 3 – Programming Fundamentals · 90 min read · 7 MCQs to check yourself

Corey Schafer – Python SQLite tutorial: creating a database, table and running queries

1. The sqlite3 module

SQLite stores a whole database in one file (e.g. school.db) and comes with Python – no server needed. The same SQL works in MySQL with a different connector (mysql.connector).

import sqlite3
con = sqlite3.connect("school.db")          # creates the file if it does not exist
cur = con.cursor()
cur.execute("DROP TABLE IF EXISTS students")
cur.execute("""CREATE TABLE students (
                   roll  INTEGER PRIMARY KEY,
                   name  TEXT NOT NULL,
                   city  TEXT,
                   marks INTEGER)""")

rows = [(1, "Ali", "Lahore", 85), (2, "Sara", "Karachi", 92),
        (3, "Bilal", "Lahore", 67), (4, "Ayesha", "Quetta", 78)]
cur.executemany("INSERT INTO students VALUES (?, ?, ?, ?)", rows)   # add records
con.commit()                                                       # save changes

cur.execute("UPDATE students SET marks = ? WHERE roll = ?", (72, 3))   # edit
cur.execute("DELETE FROM students WHERE roll = ?", (4,))               # delete
con.commit()

cur.execute("SELECT name, marks FROM students WHERE city = ? ORDER BY marks DESC", ("Lahore",))
for name, marks in cur.fetchall():
    print(name, marks)

cur.execute("SELECT COUNT(*), AVG(marks) FROM students")
count, avg = cur.fetchone()
print("Students:", count, "Average:", round(avg, 2))
con.close()

Output:

Ali 85
Bilal 72
Students: 3 Average: 83.0
Method Purpose
sqlite3.connect(file) open/create the database
con.cursor() an object that runs SQL and holds results
cur.execute(sql, params) run one statement
cur.executemany(sql, list) run it for many records
cur.fetchone() / fetchall() get one row / all rows
con.commit() save INSERT/UPDATE/DELETE permanently
con.close() close the connection

2. Why use ? placeholders?

Never build SQL by joining user input into the string:

name = "x' OR '1'='1"
unsafe = "SELECT * FROM students WHERE name = '" + name + "'"
print(unsafe)

Output:

SELECT * FROM students WHERE name = 'x' OR '1'='1'

That query returns every student – an SQL injection attack. With placeholders (WHERE name = ?, (name,)), the input is treated only as data.

3. A small menu-driven record manager (PBA style)

import sqlite3
con = sqlite3.connect(":memory:")            # temporary database in RAM for this demo
con.execute("CREATE TABLE books (id INTEGER PRIMARY KEY, title TEXT, copies INTEGER)")

def add_book(title, copies):
    con.execute("INSERT INTO books (title, copies) VALUES (?, ?)", (title, copies))
    con.commit()

def issue(title):
    row = con.execute("SELECT copies FROM books WHERE title = ?", (title,)).fetchone()
    if row is None:
        return "No such book"
    if row[0] == 0:
        return "No copies left"
    con.execute("UPDATE books SET copies = copies - 1 WHERE title = ?", (title,))
    con.commit()
    return "Issued"

add_book("Python Basics", 2)
add_book("Data Science", 1)
for t in ["Data Science", "Data Science", "Cooking", "Python Basics"]:
    print(t, "->", issue(t))
print(con.execute("SELECT title, copies FROM books ORDER BY title").fetchall())

Output:

Data Science -> Issued
Data Science -> No copies left
Cooking -> No such book
Python Basics -> Issued
[('Data Science', 0), ('Python Basics', 1)]

Short and long questions

1. Write the steps to connect Python with a database using sqlite3.

Model answer
  1. import sqlite3
  2. con = sqlite3.connect("school.db") – open/create the database
  3. cur = con.cursor() – create a cursor
  4. cur.execute("SQL…", params) – run CREATE/INSERT/UPDATE/DELETE/SELECT
  5. con.commit() – save changes; cur.fetchall() – read results
  6. con.close() – close the connection

2. Write a Python program that uses sqlite3 to create a database "clinic.db" with a table patients(id, name, age, disease). The program should insert three patients, update one patient’s disease, delete one patient, and display all remaining patients older than 30 sorted by age. Explain the purpose of commit(). (5 + 1)

Model answer
import sqlite3
con = sqlite3.connect("clinic.db")
cur = con.cursor()
cur.execute("""CREATE TABLE IF NOT EXISTS patients
               (id INTEGER PRIMARY KEY, name TEXT NOT NULL, age INTEGER, disease TEXT)""")
cur.executemany("INSERT OR REPLACE INTO patients VALUES (?, ?, ?, ?)",
                [(1, "Ahmed", 45, "Diabetes"), (2, "Fatima", 28, "Flu"), (3, "Kamran", 60, "Asthma")])
cur.execute("UPDATE patients SET disease = ? WHERE id = ?", ("Allergy", 2))
cur.execute("DELETE FROM patients WHERE id = ?", (3,))
con.commit()
cur.execute("SELECT name, age, disease FROM patients WHERE age > ? ORDER BY age", (30,))
for row in cur.fetchall():
    print(row)            # ('Ahmed', 45, 'Diabetes')
con.close()

commit() (1): INSERT, UPDATE and DELETE first happen inside a transaction; commit() makes them permanent in the database file. Without it the changes are lost when the connection closes.

3. Write Python code to display the names of students with marks above 80, sorted by marks in descending order, from table students(roll, name, marks).

Model answer
import sqlite3
con = sqlite3.connect("school.db")
cur = con.cursor()
cur.execute("SELECT name, marks FROM students WHERE marks > ? ORDER BY marks DESC", (80,))
for name, marks in cur.fetchall():
    print(name, marks)
con.close()

4. What is SQL injection? How can it be prevented in Python?

Model answer

SQL injection is an attack where a user types SQL code into an input box that is joined directly into a query, e.g. entering x' OR '1'='1 so WHERE name = 'x' OR '1'='1' returns every record (or deletes data). Prevention: use parameterised queries with placeholders – cur.execute("SELECT * FROM users WHERE name = ?", (name,)) – and validate input.

5. Write Python code to create a table Products(id, name, price) in SQLite and insert two records.

Model answer
import sqlite3
con = sqlite3.connect("shop.db")
cur = con.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS Products (id INTEGER PRIMARY KEY, name TEXT, price INTEGER)")
cur.execute("INSERT INTO Products VALUES (?, ?, ?)", (1, "Pen", 50))
cur.execute("INSERT INTO Products VALUES (?, ?, ?)", (2, "Bag", 1500))
con.commit()
con.close()

This lesson ends with a quiz of 7 MCQs. Open the lesson on PrepOasis to take it and save your progress.

Previous: 3.6 Data Normalisation: 1NF, 2NF and 3NF · Next: 3.8 Testing and Debugging: Unit Tests, Breakpoints and Watches

All lessons in Computer Science XII (HSSC-II) – FBISE Complete SLO-Based Course