Chapter 11: Database Programming

Chapter 11: Database Programming · Study Questions
DatabaseRelational modelSQLiteSQLJDBCResultSetPreparedStatementMySQLTransactions
Sercan KÜLCÜ · Giresun University · Computer Engineering

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?

idnameprice

Table created; three columns, no rows.

idnameprice1pencil10

No id given: INTEGER PRIMARY KEY assigns the largest id + 1 = 1.

idnameprice1pencil102notebook253eraser5

notebook gets id 2, eraser gets id 3.

idnameprice1pencil202notebook253eraser10

WHERE price < 20 selects two rows (10 and 5); both are doubled. notebook (25) does not change.

idnameprice1pencil202notebook25

The eraser with id = 3 is deleted.

idnameprice1pencil202notebook253ruler15

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).

idnameprice1pencil202notebook253ruler15

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; executeUpdate returns the number of affected rows: 3 (ids 1, 2, 3).
  • id > 1 selects 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.
  • execute returns 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.

peopleidnamesurnameage1AliKaya192EceDemir243CanKaya314NazDemir22result setnameageNaz22Ece24Can31

The query runs: age > 20 removes Ali, the rest are sorted by age. The cursor waits before the first row.

peopleidnamesurnameage1AliKaya192EceDemir243CanKaya314NazDemir22result setnameageNaz22Ece24Can31

rs.next() moves the cursor to row 1 and returns true.

peopleidnamesurnameage1AliKaya192EceDemir243CanKaya314NazDemir22result setnameageNaz22Ece24Can31

Columns are read by name; the counter and total are updated.

peopleidnamesurnameage1AliKaya192EceDemir243CanKaya314NazDemir22result setnameageNaz22Ece24Can31

Second row.

peopleidnamesurnameage1AliKaya192EceDemir243CanKaya314NazDemir22result setnameageNaz22Ece24Can31

Third row.

peopleidnamesurnameage1AliKaya192EceDemir243CanKaya314NazDemir22result setnameageNaz22Ece24Can31

No more rows: rs.next() is false, the loop ends.

peopleidnamesurnameage1AliKaya192EceDemir243CanKaya314NazDemir22result setnameageNaz22Ece24Can31

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)");           // 3
Show answer
  1. getString(0): column numbers start at 1. Message: column 0 out of bounds [1,1]. The correct form is getString(1) or getString("ad").
  2. An INSERT returns no result set: query does not return ResultSet. For INSERT, UPDATE and DELETE, executeUpdate is used. (In a test with the SQLite driver the row was inserted anyway.)
  3. Bora is written without quotes, so it is taken for a column name: no such column: Bora. Text values are written in single quotes; best is PreparedStatement and setString.

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.

idemail

The transaction begins: later changes are temporary until the commit.

idemail1a@x

a@x is inserted (id 1), not yet permanent.

idemail1a@x2b@x

b@x is inserted (id 2).

idemail1a@x2b@x

a@x a second time: UNIQUE constraint failed: members.email. A SQLException is thrown; the commit line is never reached.

idemail

rollback(): both inserts in the transaction are undone.

idemail

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.

The End

Chapter 11: Database Programming: Study Questions
Lecture slides: Chapter 11: Database Programming · Lecture notes
1 / 1 Sercan KÜLCÜ. All rights reserved.