A small app
After this: Build a small marks app with functions that add and find students, and read rows into objects.
On this page · 5 sections · 3 checks
You can now open a database, pass values with placeholders, and keep changes all-or-nothing. A real program puts these pieces inside functions, so the rest of the code never writes SQL. Lesson 1 ended with a bug: running the program twice added the same people twice. This lesson builds a small app properly and comes back to that bug.
Three functions
The app keeps students in marks.db. Each student has an id, a name and a city. The rest of the program needs three things from the database, so the app has three functions:
- open_db(path)openDb(path) connects to the file and makes the table if it is not there yet. It returns the connection.
- add_student(conn, name, city)addStudent(conn, name, city) runs an INSERT with two placeholders and returns the id the database gave the new row.
- students_in(conn, city)studentsIn(conn, city) runs a SELECT with one placeholder and returns a list of
Studentobjects.
The Student class is the kind you wrote in the tutorial on classes: three fields and a constructor. Turning each row into an object means the rest of the program writes s.name, and never has to know which column of the row held the name.
import sqlite3
class Student: def __init__(self, student_id, name, city): self.student_id = student_id self.name = name self.city = city
def open_db(path): conn = sqlite3.connect(path) conn.execute("CREATE TABLE IF NOT EXISTS students (id INTEGER PRIMARY KEY, name TEXT NOT NULL, city TEXT NOT NULL)") return conn
def add_student(conn, name, city): with conn: cur = conn.execute("INSERT INTO students (name, city) VALUES (?, ?)", (name, city)) return cur.lastrowid
def students_in(conn, city): sql = "SELECT id, name, city FROM students WHERE city = ? ORDER BY name, id" found = [] for student_id, name, home in conn.execute(sql, (city,)): found.append(Student(student_id, name, home)) return found
conn = open_db("marks.db")print(add_student(conn, "Ana", "Leeds"))print(add_student(conn, "Ben", "York"))print(add_student(conn, "Chloe", "Leeds"))for s in students_in(conn, "Leeds"): print(s.student_id, s.name)print(len(students_in(conn, "Paris")))conn.close()1 2 3 1 Ana 3 Chloe 0
import java.sql.*;import java.util.ArrayList;import java.util.List;
class Student { int id; String name; String city;
Student(int id, String name, String city) { this.id = id; this.name = name; this.city = city; }}
public class Main { static Connection openDb(String path) throws SQLException { Connection conn = DriverManager.getConnection("jdbc:sqlite:" + path); try (Statement st = conn.createStatement()) { st.execute("CREATE TABLE IF NOT EXISTS students (id INTEGER PRIMARY KEY, name TEXT NOT NULL, city TEXT NOT NULL)"); } return conn; }
static int addStudent(Connection conn, String name, String city) throws SQLException { String sql = "INSERT INTO students (name, city) VALUES (?, ?)"; try (PreparedStatement ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) { ps.setString(1, name); ps.setString(2, city); ps.executeUpdate(); ResultSet keys = ps.getGeneratedKeys(); keys.next(); return keys.getInt(1); } }
static List<Student> studentsIn(Connection conn, String city) throws SQLException { String sql = "SELECT id, name, city FROM students WHERE city = ? ORDER BY name, id"; List<Student> found = new ArrayList<>(); try (PreparedStatement ps = conn.prepareStatement(sql)) { ps.setString(1, city); ResultSet rs = ps.executeQuery(); while (rs.next()) { found.add(new Student(rs.getInt("id"), rs.getString("name"), rs.getString("city"))); } } return found; }
public static void main(String[] args) throws SQLException { try (Connection conn = openDb("marks.db")) { System.out.println(addStudent(conn, "Ana", "Leeds")); System.out.println(addStudent(conn, "Ben", "York")); System.out.println(addStudent(conn, "Chloe", "Leeds")); for (Student s : studentsIn(conn, "Leeds")) { System.out.println(s.id + " " + s.name); } System.out.println(studentsIn(conn, "Paris").size()); } }}1 2 3 1 Ana 3 Chloe 0
Here is what happens when it runs on a folder with no marks.db:
- The program opens the file, which SQLite creates, and makes the table.
- It adds Ana, Ben and Chloe. Each INSERT runs inside its own transaction and is committed. cur.lastrowidgetGeneratedKeys() gives back the id SQLite chose for the new row, so the program prints
1,2and3. - It asks for the students in Leeds. The SELECT returns two rows, and the function turns each into a
Student. The program prints1 Anaand3 Chloe. - It asks for Paris. No row matches, so the list is empty and the program prints
0.
Here is the SELECT the function sends for Leeds, with the value written in, on a table holding the three students:
The bug, again
Run the app a second time in the same folder. The file already holds Ana, Ben and Chloe, and the app adds them again:
4561 Ana4 Ana3 Chloe6 Chloe0The new rows get the ids 4, 5 and 6, and Leeds now has two Anas and two Chloes. The database did what it was asked; the program asked for the wrong thing. There are two usual fixes:
- Add a rule to the table, such as
UNIQUE (name, city), so the database refuses a second Ana from Leeds. The INSERT then raises an error that add_studentaddStudent must catch, as the transfer did. - Or ask first, with a SELECT and a placeholder, and add the student only when no row comes back.
The rule is the safer of the two, because it holds for every program that uses the file, not only this one.
Reading a column by its name
So far the code reads a row by position: the first column, the second column. If someone reorders the columns in the SELECT, that code silently reads the wrong one. Both languages can read a column by its name instead.
import sqlite3
conn = sqlite3.connect(":memory:")conn.row_factory = sqlite3.Rowconn.execute("CREATE TABLE students (id INTEGER PRIMARY KEY, name TEXT NOT NULL)")conn.execute("INSERT INTO students (name) VALUES ('Ana'), ('Ben')")
row = conn.execute("SELECT id, name FROM students WHERE id = ?", (2,)).fetchone()print(row["name"])print(row[1])Ben Ben
import java.sql.*;
public class Main { public static void main(String[] args) throws SQLException { Connection conn = DriverManager.getConnection("jdbc:sqlite::memory:"); Statement st = conn.createStatement(); st.execute("CREATE TABLE students (id INTEGER PRIMARY KEY, name TEXT NOT NULL)"); st.execute("INSERT INTO students (name) VALUES ('Ana'), ('Ben')");
PreparedStatement ps = conn.prepareStatement("SELECT id, name FROM students WHERE id = ?"); ps.setInt(1, 2); ResultSet rs = ps.executeQuery(); rs.next(); System.out.println(rs.getString("name")); System.out.println(rs.getString(2)); conn.close(); }}Ben Ben
Check yourself
No student lives in Paris. What does students_in(conn, "Paris")studentsIn(conn, "Paris") give back?
The app ran once and printed 1, 2, 3, then 1 Ana, 3 Chloe, then 0. You run it again in the same folder, so marks.db is kept. What does the second run print?
import sqlite3
class Student: def __init__(self, student_id, name, city): self.student_id = student_id self.name = name self.city = city
def open_db(path): conn = sqlite3.connect(path) conn.execute("CREATE TABLE IF NOT EXISTS students (id INTEGER PRIMARY KEY, name TEXT NOT NULL, city TEXT NOT NULL)") return conn
def add_student(conn, name, city): with conn: cur = conn.execute("INSERT INTO students (name, city) VALUES (?, ?)", (name, city)) return cur.lastrowid
def students_in(conn, city): sql = "SELECT id, name, city FROM students WHERE city = ? ORDER BY name, id" found = [] for student_id, name, home in conn.execute(sql, (city,)): found.append(Student(student_id, name, home)) return found
conn = open_db("marks.db")print(add_student(conn, "Ana", "Leeds"))print(add_student(conn, "Ben", "York"))print(add_student(conn, "Chloe", "Leeds"))for s in students_in(conn, "Leeds"): print(s.student_id, s.name)print(len(students_in(conn, "Paris")))conn.close()import java.sql.*;import java.util.ArrayList;import java.util.List;
class Student { int id; String name; String city;
Student(int id, String name, String city) { this.id = id; this.name = name; this.city = city; }}
public class Main { static Connection openDb(String path) throws SQLException { Connection conn = DriverManager.getConnection("jdbc:sqlite:" + path); try (Statement st = conn.createStatement()) { st.execute("CREATE TABLE IF NOT EXISTS students (id INTEGER PRIMARY KEY, name TEXT NOT NULL, city TEXT NOT NULL)"); } return conn; }
static int addStudent(Connection conn, String name, String city) throws SQLException { String sql = "INSERT INTO students (name, city) VALUES (?, ?)"; try (PreparedStatement ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) { ps.setString(1, name); ps.setString(2, city); ps.executeUpdate(); ResultSet keys = ps.getGeneratedKeys(); keys.next(); return keys.getInt(1); } }
static List<Student> studentsIn(Connection conn, String city) throws SQLException { String sql = "SELECT id, name, city FROM students WHERE city = ? ORDER BY name, id"; List<Student> found = new ArrayList<>(); try (PreparedStatement ps = conn.prepareStatement(sql)) { ps.setString(1, city); ResultSet rs = ps.executeQuery(); while (rs.next()) { found.add(new Student(rs.getInt("id"), rs.getString("name"), rs.getString("city"))); } } return found; }
public static void main(String[] args) throws SQLException { try (Connection conn = openDb("marks.db")) { System.out.println(addStudent(conn, "Ana", "Leeds")); System.out.println(addStudent(conn, "Ben", "York")); System.out.println(addStudent(conn, "Chloe", "Leeds")); for (Student s : studentsIn(conn, "Leeds")) { System.out.println(s.id + " " + s.name); } System.out.println(studentsIn(conn, "Paris").size()); } }}In the program that reads Ben's row, someone changes the query from SELECT id, name … to SELECT name, id …. Which way of reading the name gives Ben both before and after the change?
Honesty notes
- Put the SQL of an app inside functions that open the database, add a record and find records.
- Read back the id the database gave a new row: lastrowid in Python, getGeneratedKeys in Java.
- Turn each row into an object of a small class, and return an empty list when nothing matches.
- Read a column by its name rather than its position, so a change in column order does not break the code.
- Say why the app added the same students twice, and how a UNIQUE rule or a check first would stop it.