Chapter 11: Database Programming
Multiple Choice · Database Concepts
Question 1: File or Database?
A school's grade records are kept in a CSV file. When many teachers start entering grades at the same time, which problem most calls for moving to a database?
B: In a flat file, if two programs write at the same time, one can overwrite the other's change or the file can be left half-written; a database manages this with locking and transactions (all or nothing). Files are persistent too; a CSV can be read from Java with BufferedReader and has no limit like 1 MB.
Multiple Choice · Database Concepts
Question 2: Table, Row, Primary Key
students(id INTEGER PRIMARY KEY, name TEXT, dept TEXT) table: which statement is true?
C: A row is all the information about one entity (a student), a column is one property (name TEXT). The primary key identifies each row uniquely: with the same id, the second row is rejected. Uniqueness does not pass to other columns automatically; for that a UNIQUE constraint is written. Java analogy: table ≈ class, column ≈ field, row ≈ object.
Multiple Choice · SQLite
Question 3: Features of SQLite
Which statement is true about SQLite?
D: SQLite is embedded and serverless: a single driver jar is added to the project, jdbc:sqlite:school.db creates the file if it does not exist. A temporary in-memory database is opened only with jdbc:sqlite::memory:. Because it allows only one writer at a time, server-based systems such as MySQL or PostgreSQL are preferred for large multi-user systems.
Step-by-Step Trace · SQL Basics
Question 4: SQL Statements and id
These SQL statements run in order on an empty database. What does the table look like after each statement, and what does the final SELECT return?
Table created; three columns, no rows.
No id given: INTEGER PRIMARY KEY assigns the largest id + 1 = 1.
notebook gets id 2, eraser gets id 3.
WHERE price < 20 selects two rows (10 and 5); both are doubled. notebook (25) does not change.
The eraser with id = 3 is deleted.
The largest id is now 2: ruler gets id 3. The number of the deleted row was reused (it would have been 4 with AUTOINCREMENT).
SELECT only reads; three rows are returned.
CREATE TABLE product (id INTEGER PRIMARY KEY, name TEXT, price INTEGER); INSERT INTO product(name, price) VALUES ('pencil', 10); INSERT INTO product(name, price) VALUES ('notebook', 25); INSERT INTO product(name, price) VALUES ('eraser', 5); UPDATE product SET price = price * 2 WHERE price < 20; DELETE FROM product WHERE id = 3; INSERT INTO product(name, price) VALUES ('ruler', 15); SELECT * FROM product;
Multiple Choice · SQL Basics
Question 5: Filter, Sort, Limit
student(name, score) table has (Ece, 85), (Can, 70), (Ada, 85), (Efe, 65), (Naz, 92). In which order does the query return which names?
SELECT name FROM student WHERE score >= 70 ORDER BY score DESC, name LIMIT 3;
A: WHERE score >= 70 removes Efe. ORDER BY score DESC sorts from largest to smallest: Naz (92), then the two with 85; on a tie the second criterion name in ascending order: Ada, Ece. LIMIT 3 takes the first three rows; Can (70) is left out.
Output Question · SQL Basics
Question 6: Aggregate Functions
student(name, score) table has the rows (Ece 85, Can 70, Ada 85, Efe 65, Naz 92). Which four values does this query return?
SELECT COUNT(*), AVG(score), MAX(score), MIN(score) FROM student WHERE score < 90;
Show answer
4 | 76.25 | 85 | 65
WHERE filters the rows first: Naz with 92 is removed, 4 rows remain (85, 70, 85, 65). The aggregate functions work on these rows: COUNT 4, AVG = 305 / 4 = 76.25, MAX 85, MIN 65. The result is a single row.
Multiple Choice · JDBC
Question 7: The Closing Order of Resources
try (Connection conn = ...; Statement st = conn.createStatement(); ResultSet rs = st.executeQuery(sql)) { ... } — when the block ends, in what order are the resources closed?
B: try-with-resources closes resources in the reverse of the order they were opened; the closing happens even if the block ends with an exception. Since a ResultSet depends on a Statement, and a Statement on a Connection, this order is the natural one. Unclosed connections can leave the SQLite file locked.
Output Question · Basic Operations
Question 8: Return Values of the execute Methods
t(id INTEGER PRIMARY KEY, name TEXT) table is empty. What does the program print?
int a = st.executeUpdate(
"INSERT INTO t(name) VALUES ('x'), ('y'), ('z')");
int b = st.executeUpdate(
"UPDATE t SET name = 'w' WHERE id > 1");
int c = st.executeUpdate(
"DELETE FROM t WHERE name = 'q'");
boolean d = st.execute("SELECT * FROM t");
System.out.println(a + " " + b + " " + c + " " + d);Show answer
3 2 0 true
- A single INSERT adds three rows;
executeUpdatereturns the number of affected rows: 3 (ids 1, 2, 3). id > 1selects two rows: 2.- No row has the name 'q': there is no error, 0 is returned. That is why giving the delete message based on this number is correct.
executereturns true for a statement that produces a result set, false for other statements.
Step-by-Step Trace · Basic Operations
Question 9: Average with a ResultSet
people table is as shown in the figure. What does the program print? The arrow shows the cursor in the result set.
The query runs: age > 20 removes Ali, the rest are sorted by age. The cursor waits before the first row.
rs.next() moves the cursor to row 1 and returns true.
Columns are read by name; the counter and total are updated.
Second row.
Third row.
No more rows: rs.next() is false, the loop ends.
77 / 3; without (double) it would be integer division giving 25. When the block ends, rs and st are closed.
String sql = "SELECT name, age FROM people "
+ "WHERE age > 20 ORDER BY age";
try (Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(sql)) {
int n = 0, total = 0;
while (rs.next()) {
String name = rs.getString("name");
int age = rs.getInt("age");
n++;
total += age;
System.out.println(name + " " + age);
}
System.out.println(n + " people, average "
+ (double) total / n);
}Spot the Bug · Basic Operations
Question 10: Three Bugs
people(id, name, surname, age) table: each of these lines throws a SQLException. Write the causes and the fixes.
ResultSet rs = st.executeQuery(
"SELECT name FROM people");
rs.next();
String name = rs.getString(0); // 1
st.executeQuery("INSERT INTO people(name, surname, age) "
+ "VALUES ('Ece', 'Er', 20)"); // 2
st.executeUpdate("INSERT INTO people(name, surname, age) "
+ "VALUES (Bora, 'Er', 20)"); // 3Show answer
getString(0): column numbers start at 1. Message:column 0 out of bounds [1,1]. The correct form isgetString(1)orgetString("ad").- An INSERT returns no result set:
query does not return ResultSet. For INSERT, UPDATE and DELETE,executeUpdateis used. (In a test with the SQLite driver the row was inserted anyway.) Borais written without quotes, so it is taken for a column name:no such column: Bora. Text values are written in single quotes; best isPreparedStatementandsetString.
Multiple Choice · PreparedStatement
Question 11: The Order of Placeholders
conn.prepareStatement("UPDATE people SET age = ? WHERE name = ? AND surname = ?") is used to set Ece Demir's age to 25. Which calls are correct?
C: The ? placeholders are numbered from 1 in the order they appear in the SQL text: first the age in SET, then the name and surname in WHERE. Index 0 is invalid. Each ? is a single value; joining name and surname in one parameter breaks the match. Then executeUpdate() is called without parameters.
Output Question · PreparedStatement
Question 12: Numeric Injection
k2 table has three rows with ids 1, 2, 3. The user types 0 OR 1=1 as the number of the record to delete. First a PreparedStatement, then concatenated SQL runs. Which two numbers are printed?
String input = "0 OR 1=1";
try (PreparedStatement ps = conn.prepareStatement(
"DELETE FROM k2 WHERE id = ?")) {
ps.setString(1, input);
System.out.println(ps.executeUpdate());
}
System.out.println(st.executeUpdate(
"DELETE FROM k2 WHERE id = " + input));Show answer
0 3
With a PreparedStatement the input is only a value: id = '0 OR 1=1' matches no row, 0 rows are deleted.
With concatenation the input becomes part of the SQL: DELETE FROM k2 WHERE id = 0 OR 1=1. 1=1 is true for every row, so the whole table is deleted: 3. No quote is needed for an injection; numeric fields must be protected as well. Input must always be passed with ? and setXxx.
Coding Question · PreparedStatement
Question 13: Average Age by Surname
static double averageAge(Connection conn, String surname) throws SQLException — write this method: it returns the average age of the people with the given surname, using AVG; the input must not be added to the SQL text, and the resources it opens must be closed. With the people table holding Ali Kaya 19, Ece Demir 24, Can Kaya 31, Naz Demir 22, what is returned for "Kaya" and "Nobody"?
Show answer
static double averageAge(Connection conn, String surname) throws SQLException { String sql = "SELECT AVG(age) FROM people WHERE surname = ?"; try (PreparedStatement ps = conn.prepareStatement(sql)) { ps.setString(1, surname); try (ResultSet rs = ps.executeQuery()) { return rs.next() ? rs.getDouble(1) : 0; } } }
"Kaya": (19 + 31) / 2 = 25.0. "Nobody": even with no matching rows, AVG returns a single row whose value is NULL; getDouble gives, for NULL, 0.0 (to tell them apart, use rs.wasNull()). The connection is a method parameter; the code that opens it closes it.
Multiple Choice · MySQL
Question 14: From SQLite to MySQL
A JDBC program that works with SQLite is to be moved to a MySQL server. What usually changes?
D: The JDBC interfaces are the same; thanks to polymorphism the driver supplies the real object. What changes: a URL such as jdbc:mysql://localhost:3306/testdb, getConnection(url, user, password) and the mysql-connector-j jar. The basic SQL (CREATE, INSERT, SELECT...) is largely the same; small differences (e.g. the auto-increment key syntax) can exist.
Multiple Choice · Transactions
Question 15: ACID
“A second after a transfer is committed, even if the power goes out, the transfer appears to have been made when the system is restarted.” Which ACID property is this?
A: Durability: a committed change has been written to permanent storage and is not lost. Atomicity means a transaction is applied entirely or not at all; consistency means the constraints (e.g. balance ≥ 0) hold at the end of the transaction; isolation means concurrent transactions do not see each other's half-finished state.
Step-by-Step Trace · Transactions
Question 16: UNIQUE Error and rollback
members(id INTEGER PRIMARY KEY, email TEXT UNIQUE) table is empty. Three e-mails are inserted within a single transaction. What does the program print, and how many rows remain in the table? Dashed lines have not been committed yet.
The transaction begins: later changes are temporary until the commit.
a@x is inserted (id 1), not yet permanent.
b@x is inserted (id 2).
a@x a second time: UNIQUE constraint failed: members.email. A SQLException is thrown; the commit line is never reached.
rollback(): both inserts in the transaction are undone.
finally turns auto-commit back on. 0 rows in the table: all or nothing.
conn.setAutoCommit(false); String sql = "INSERT INTO members(email) VALUES(?)"; try (PreparedStatement ps = conn.prepareStatement(sql)) { for (String e : new String[] {"a@x", "b@x", "a@x"}) { ps.setString(1, e); ps.executeUpdate(); } conn.commit(); System.out.println("saved"); } catch (SQLException ex) { conn.rollback(); System.out.println("rolled back"); } finally { conn.setAutoCommit(true); }
Output Question · Transactions
Question 17: Without a Transaction
members(id INTEGER PRIMARY KEY, email TEXT UNIQUE) table is empty and the connection has the default setting (auto-commit on). After the code runs, how many rows remain in the table, and why?
String sql = "INSERT INTO members(email) VALUES(?)";
try (PreparedStatement ps = conn.prepareStatement(sql)) {
for (String e : new String[] {"a@x", "b@x", "a@x"}) {
ps.setString(1, e);
ps.executeUpdate();
}
} catch (SQLException ex) {
System.out.println("error");
}Show answer
2 rows (a@x and b@x). With auto-commit on, each executeUpdate is permanent on its own: the first two inserts are written immediately, the third is rejected because of UNIQUE and there is no transaction to roll back. The list is left half-done instead of “all or nothing”. With setAutoCommit(false), commit() and, on error, rollback(), the table would have stayed empty. Commands that only make sense together (a transfer, an order and its items) are therefore run in a single transaction.