Object-Oriented Programming with Java · Lecture Notes
Chapter 11: Database Programming
A program's variables and objects live in memory and disappear when the program ends. Student grades, bank accounts, and sensor readings, however, must be kept for years, found quickly, and changed safely by many programs at the same time. Databases do this job. The chapter begins with the idea of a database, how it differs from a file, and the relational model. It then turns to SQLite, an embedded database, and to SQL, the common language of relational databases. The SQL part shows how to create tables, insert, query, update, and delete records, and how to join and group tables. The following sections cover JDBC, Java's database interface, and the safe way to use user input. The last sections show how to turn rows into objects and how transactions run several statements as a single unit of work. All code was run with JDK 21 and the SQLite JDBC driver.
Learning outcomes
- Explain the concepts
- Explain why a database is needed, how it differs from a flat file, and what the relational model (table, row, column, primary key) is.
- Write SQL
- Write
CREATE TABLE,INSERT,SELECT,UPDATE, andDELETEstatements; narrow a query withWHERE,ORDER BY, andLIMIT. - Use relationships
- Link tables with a foreign key; combine them with
JOIN; group rows withGROUP BYandHAVING; compareNULLvalues correctly. - Work with JDBC
- Connect to SQLite from Java with
Connection,Statement, andResultSet, and insert, read, update, and delete records; close resources with try-with-resources. - Security and integrity
- Prevent SQL injection with
PreparedStatement; run several statements as one transaction withcommitandrollback. - Map rows to objects
- Turn the rows of a query result into objects and collect a table's SQL in a data access object (DAO).
11.1The idea of a database
This section explains what a database is, which problem it solves, and how it organizes data. There is no code here; the concepts defined below underlie all of the JDBC code that follows.
11.1.1Why do we need a database?
When a Java program executes int total = 87;, the value 87 is placed somewhere in RAM, the main memory. Objects live in the heap. This memory is fast but not persistent. When the program ends, the operating system reclaims its memory, and the variables and objects are gone. If the power fails, the contents of memory are erased as well.
Yet much data must outlive the program. A student's midterm grade is needed throughout the semester, a bank balance for years, a game's high score every time the game starts. Storing data this way is called persistent storage. Persistent storage lives on a medium such as a disk, which keeps its contents when the power is off.
A database is an organized collection of data that can be queried easily. The software that creates, protects, queries, and updates a database is called a database management system (DBMS).
In everyday speech the two are often confused: people say "the MySQL database", but MySQL is really a DBMS. The database is the set of tables and the records in them that the system manages. Figure 11.1 shows the difference between the two kinds of storage. While running, a program works on data in memory and writes whatever must last to the database (INSERT, UPDATE). When the program starts again, the data is read back from disk (SELECT).
school.db) persists.An analogy helps. A database is like a library's catalogued archive. Without a catalog, finding a book would mean walking past every shelf. With one, the book's location is found in a few steps. A database likewise finds the record you want among millions without reading all the data from beginning to end.
11.1.2File or database?
A database is not the only way to store data persistently. A program can also write data to a text file or to a CSV (comma-separated values) file. For a settings file, a log, or a short list, a file is enough and simpler. As data grows and becomes more complex, and as several programs begin to use the same data, the limits of files appear. Table 11.1 compares the two approaches on six points.
| Feature | Flat file (txt, csv) | Database |
|---|---|---|
| Search | The file is read from start to end | Fast with an index; a one-line SQL query |
| Update | Often the whole file is rewritten | Only the affected row changes |
| Concurrent access | Data can be corrupted if two programs write at once | Safe, thanks to locking and transactions |
| Consistency | Format checking is left entirely to the programmer | Data types and constraints (NOT NULL, UNIQUE, CHECK) |
| Security | File permissions: all or nothing | Permissions per user, table, and column (in server DBMSs; SQLite relies on file permissions) |
| After a failure | A write interrupted midway can corrupt the file | An interrupted transaction is rolled back |
Each difference in the table corresponds to a concrete problem. If a school's student list is in a CSV file, finding one student among 20,000 rows means reading the file line by line. Changing one student's phone number usually means reading the whole file, changing it in memory, and writing it out again, because if a line in the middle of a text file grows longer, every byte after it shifts.
The most serious problem is concurrent access. If two teachers enter grades at the same time, both read the file, make their own changes, and write it back. The second one to write overwrites the first one's change without noticing it. A DBMS manages this situation with locks and transactions. If the power fails during a write, the file may be left half-written; a database rolls back the unfinished transaction at startup.
The difference in consistency is also large. Nothing stops someone from typing "twenty" instead of an age into a cell of a CSV file; every program that reads the file must check for this error itself. In a database the rules are part of the table definition, and a record that violates them is rejected up front. Figure 11.2 summarizes the structural difference: with a file, the program accesses the file directly; with a database, a DBMS sits in between.
11.1.3Core features
Four core features make databases superior to files.
Fast access to data. A database keeps extra structures called indexes for frequently searched columns. With an index, a record among millions is found quickly without looking at every row.
Column-level security. With a file, permissions usually apply to the whole file: whoever can read the file can read everything in it. A DBMS can grant permissions per table or even per column (field). In a company database, for example, only the accounting department may see the salary column, while other departments can read the name and phone columns of the same table. These permissions are granted in server DBMSs (for example with GRANT in PostgreSQL or MySQL); SQLite has no users or permissions, and access depends on file permissions.
Platform-independent, standard interfaces. SQL is a standard; its core statements are the same in all relational databases. On the Java side there is likewise a single set of interfaces, JDBC. The same Java code reaches different databases when the driver is swapped.
Independence from the file structure. The program does not know in which file, in what order, or in what format the data is stored on disk. Its job is to say what it wants in SQL; the DBMS decides how to find the data (Figure 11.3). Because of this separation, when the DBMS adds an index or changes how the data is laid out, the program code does not change.
Two more features come on top of these four. The first is integrity constraints: rules such as "this column cannot be empty", "this value cannot repeat", or "age cannot be negative" are written into the table, and the DBMS rejects any record that violates them. The second is transaction support: several changes are either all applied or none is.
11.1.4The relational model
The most common kind of database today is the relational database. Its name comes from the fact that data is kept in tables based on the mathematical notion of a relation.
The relational model keeps data in tables made of rows and columns. A column is one attribute of the data; it has a name and a data type. A row (record) holds all the information about one entity. A primary key is a column that identifies each row of the table uniquely; no two rows can have the same primary key.
users table. Its columns are id, name, and email; each row is one user; id is the primary key.Figure 11.4 shows the users table used throughout the chapter. The table has three columns. The type of the name column is text (TEXT), and the type of the id column is integer (INTEGER). The highlighted second row holds everything about the user named Ayşe Demir: her ID is 2 and her e-mail is ayse@example.com.
Why is a primary key needed? Two users can have the same name; if two "Ahmet Yılmaz" records cannot be told apart, it is unclear which one to update. Even first and last name together are not unique. That is why each row is given a number that identifies it and nothing else. The number never changes and is never given to another row. The primary key is also used by other tables to point to this row.
An analogy with Java is useful. A table corresponds to a class, a column to a field, and a row to an object. The users table resembles a User class with the fields int id, String name, and String email; each row is an object of that class. The analogy is not exact: a table holds only data and has no methods. But this mapping is used directly when rows are converted to objects.
Confusing rows with columns. A column is an attribute found in every record (email). A row is one record and carries all of its attributes (Ayşe Demir's ID, name, and e-mail). "Adding a new student to the table" means adding a new row; "adding a birth date for students" means adding a new column.
11.1.5Kinds of databases
Databases are grouped by the way they organize data. Three groups matter for this course.
Relational databases keep data in tables and are queried with SQL. Oracle, SQL Server, MySQL, and PostgreSQL belong to this group. These systems run as a server; many clients connect to the same database over the network. Most usage, about 77 percent, is in this group.
NoSQL and search systems do not use tables. They keep data as documents (JSON-like records), key-value pairs, or a search index. MongoDB is a document database and Elasticsearch is a search engine. They are used in particular scenarios, for example for data whose structure changes often or whose volume is very large. Their share of usage is about 23 percent (Figure 11.5).
Embedded relational databases run not as a separate server but as a library inside the program. The best known is SQLite. They are common where little data is shared and a single program stores its own data: phone apps, browsers, embedded devices.
The examples in this chapter use SQLite, which is the easiest to set up. There is no server to install, no user to define, and no network to configure. The SQL statements and the JDBC code are almost the same in other relational databases. What you learn with SQLite carries over directly to MySQL or PostgreSQL; only the connection URL and the driver change.
11.2SQLite
11.2.1What is SQLite?
SQLite is an open-source, free relational database written in C. The following features set it apart from other relational systems.
- It is embedded: it runs as a library inside the program. When a Java program calls SQLite, no separate process starts; the database code runs in the program's own process.
- It is serverless: no separate server program, installation, or database administrator is needed.
- It is self-contained: all tables, indexes, and the schema are stored in a single disk file, for example
sample.db. Backing up the database or moving it to another machine means copying this file. - It is cross-platform: the same
.dbfile opens on Windows, Linux, macOS, and Android.
SQLite is the most widely used embedded relational database in the world. It is found in every Android phone, every major browser, and many desktop programs. Common uses are mobile apps, embedded systems, small-scale applications, and desktop programs such as browsers and e-mail clients. For electrical and electronics engineering, embedded systems are especially important: a measuring device can store the values it reads in a SQLite file and query them later.
There is also a clear case where SQLite is not suitable: large systems in which many users write at the same time over a network. SQLite allows only one writer at a time. For the thousands of concurrent orders of an e-commerce site, a server-based system such as MySQL or PostgreSQL is needed.
11.2.2Server-based and embedded databases
Figure 11.6 shows the difference between the two architectures. A server-based database involves two processes: the Java program and the database server. The program connects to the server over the network; MySQL's default port is 3306. A user name and password are supplied when connecting. The server writes the data to files on disk; the program never sees these files.
An embedded database involves a single process. The SQLite library lives inside the Java program and reads and writes the .db file directly. There is no network, user name, or password. Table 11.2 summarizes the differences.
| Server-based | SQLite | |
|---|---|---|
| Setup | Install a server; define users and passwords | Add a single jar to the project |
| Data | Many files managed by the server | A single .db file |
| Concurrent writes | Many users | One writer at a time |
11.2.3The driver, DB Browser, and running the code
For Java to talk to SQLite, a JDBC driver is needed. The common driver for SQLite is Xerial's sqlite-jdbc library (github.com/xerial/sqlite-jdbc). The driver is a single jar file, for example sqlite-jdbc-3.40.0.0.jar. This jar contains both the Java classes and SQLite's native library compiled for each operating system, so SQLite does not need to be installed separately.
To look inside the database file you can use DB Browser for SQLite (sqlitebrowser.org). This program opens a .db file, shows the tables and rows visually, and runs SQL statements. It is very useful for checking what a Java program has changed. After the program inserts a row, you refresh the table in DB Browser and see that the row was really added.
In Eclipse, the driver is added to the project as follows. Put the jar file in a lib folder in the project. Right-click the project and choose Build Path → Configure Build Path…. In the Libraries tab select Classpath, add the jar with Add JARs…, and close with Apply and Close. From the command line, compiling and running look like this:
javac Connect.java
java -cp ".;sqlite-jdbc-3.40.0.0.jar" ConnectThe first line compiles the program. The driver is not needed for compiling, because the java.sql package that the program uses ships with the JDK. The second line runs the program. The -cp option gives the classpath: the dot is for Connect.class in the working folder, and the jar is for the driver. On Windows, classpath entries are separated by a semicolon (;); on Linux and macOS, by a colon (:). The driver is needed only at run time; if the jar is not on the classpath, the program compiles but fails when it tries to connect. The message in that case has the form "No suitable driver found …".
11.3SQL basics
Before connecting to a database from Java, you need to know the database's language. A Java program sends SQL statements to the database as text; the database parses and runs them. The statements in this section work the same in DB Browser for SQLite and inside a Java program.
11.3.1Common SQL statements
SQL (Structured Query Language) is the common language of relational databases. An SQL statement that asks the database for data is called a query.
Unlike Java, SQL is a declarative language. To search an array in Java you write a loop: you say step by step which element to look at and in what order. In SQL you describe only the result you want: "get the players whose score is above 70." The DBMS decides how to produce the result. Table 11.3 lists the five most commonly used statements.
| Statement | Purpose | Example | CRUD |
|---|---|---|---|
CREATE TABLE | Creates a new table | CREATE TABLE users (id INTEGER, name TEXT) | — |
INSERT INTO | Inserts a new record | INSERT INTO users(name) VALUES('Ali') | Create |
SELECT | Queries a table | SELECT * FROM users | Read |
UPDATE | Updates existing records | UPDATE users SET name = 'Efe' WHERE id = 1 | Update |
DELETE | Deletes records | DELETE FROM users WHERE id = 1 | Delete |
The four basic operations on persistent data are known as CRUD. The name comes from the initials of the operations: create, read, update, and delete. Almost every database application is a combination of these four operations. Figure 11.7 shows which SQL statement corresponds to each letter. CREATE TABLE is not part of CRUD; it creates the structure of the table, not data.
INSERT), reading (SELECT), updating (UPDATE), and deleting (DELETE) rows of a table.The syntax rules are short. SQL keywords are case-insensitive: select and SELECT are the same. For readability, keywords are written in upper case and table and column names in lower case. Text values go inside single quotes: 'Ali'. Double quotes in SQL are used for names, not values; that is why SQL inside a Java string writes text values with single quotes, and the two languages do not get mixed up. The asterisk in SELECT * means "all columns". WHERE selects the rows to which the statement applies.
11.3.2CREATE TABLE, data types, and constraints
A table is defined by its name and its columns. Each column has a name, a type, and optional constraints. The following statement creates a table of members:
CREATE TABLE IF NOT EXISTS members (
id INTEGER PRIMARY KEY, -- unique
name TEXT NOT NULL, -- required
email TEXT UNIQUE, -- no repeats
age INTEGER CHECK (age >= 0)
)Each part of the statement has a job. IF NOT EXISTS prevents an error when the table already exists. The program can run this statement every time it starts: the first time the table is created, and later the statement does nothing. Parts that start with -- are comments that run to the end of the line in SQL, like // in Java.
INTEGER PRIMARY KEY has a special meaning in SQLite. This column is the row's internal number (rowid). If no value is given on insert, SQLite assigns one more than the largest id in the table, or 1 if the table is empty. The program therefore does not need to generate numbers.
Constraints are rules written into the table. NOT NULL says the column cannot be left empty, UNIQUE says a value cannot repeat in two rows, and CHECK says the given condition must hold in every row. If a constraint is violated, the statement is rejected and the table does not change. The following experiment sends nine inserts to this table and prints the message JDBC gives for each rejected insert:
accepted: INSERT INTO members(name, email, age) VALUES ('Ada', 'ada@x', 20)
[SQLITE_CONSTRAINT_NOTNULL] A NOT NULL constraint failed (NOT NULL constraint failed: members.name)
[SQLITE_CONSTRAINT_CHECK] A CHECK constraint failed (CHECK constraint failed: age >= 0)
[SQLITE_CONSTRAINT_UNIQUE] A UNIQUE constraint failed (UNIQUE constraint failed: members.email)
[SQLITE_CONSTRAINT_PRIMARYKEY] A PRIMARY KEY constraint failed (UNIQUE constraint failed: members.id)
accepted: INSERT INTO members(name) VALUES ('Naz')
accepted: INSERT INTO members(id, name) VALUES (10, 'Ece')
accepted: INSERT INTO members(name) VALUES ('Nur')
accepted: INSERT INTO members(name, age) VALUES ('Ali', 'twenty')
1 Ada ada@x 20 integer
2 Naz null null null
10 Ece null null null
11 Nur null null null
12 Ali null twenty textEach message corresponds to one constraint. The row without a name is rejected with NOT NULL constraint failed: members.name, and the row with age −3 with CHECK constraint failed: age >= 0. The row that reuses Ada's e-mail runs into the UNIQUE constraint, and the second row with id 1 runs into the primary key. The [SQLITE_CONSTRAINT_…] part at the start of the message is an error code added by the driver; the actual message in parentheses comes from SQLite itself.
The last lines of the output show how INTEGER PRIMARY KEY behaves. Naz gets number 2. When Ece is given 10 by hand, the next row (Nur) gets 11: the largest id + 1. Numbers 3 to 9 stay unused; this is not a problem, because a primary key does not have to be consecutive, only unique.
The last row reveals a subtlety specific to SQLite: the text 'twenty' could be stored in an INTEGER column. SQLite is flexibly typed; a column's type is only a suggestion (type affinity). If a value can be converted to a number it is stored as a number, and otherwise as text. CHECK (age >= 0) did not stop this row either, because in SQLite comparisons any text value counts as greater than any number. MySQL and PostgreSQL reject such a value. So on the Java side the value must be given with the right type, and numbers should be sent with typed methods such as setInt. Table 11.4 lists the Java counterparts of the SQLite types.
| SQLite type | Java counterpart | Read method |
|---|---|---|
INTEGER | int, long | getInt, getLong |
REAL | double | getDouble |
TEXT | String | getString |
BLOB | byte[] | getBytes |
NULL | no value | getString → null |
BLOB (binary large object) is a raw byte array; an image or a measurement record can be stored with this type. NULL is not a type but a special marker that indicates the absence of a value. How it behaves in comparisons is important in its own right.
11.3.3SQL statements step by step
How the five basic statements change a table can be followed by running them in order on an empty database. The first statement creates the table:
CREATE TABLE users (id INTEGER PRIMARY KEY,
name TEXT, email TEXT)After this statement the table has three columns but no rows. Two inserts follow:
INSERT INTO users(name, email)
VALUES('Ahmet Yılmaz', 'ahmet@example.com')INSERT INTO users(name, email)
VALUES('Ayşe Demir', 'ayse@example.com')The inserts do not give an id; only the name and email columns are named, and their values are given in the same order inside VALUES. SQLite assigns 1 to the first row and the largest id + 1 = 2 to the second. Each insert affects one row. Then the first row is updated and deleted, and finally the table is read:
UPDATE users SET name = 'Mehmet Akdeniz'
WHERE id = 1DELETE FROM users WHERE id = 1SELECT * FROM usersIf the statements are run one by one from a Java program and the table is printed after each, the result is Table 11.5. The "Rows affected" column is the count that JDBC reports for each statement.
| Statement | Rows affected | State of the table |
|---|---|---|
CREATE TABLE users … | 0 | (empty) |
INSERT … 'Ahmet Yılmaz' | 1 | (1, Ahmet Yılmaz, ahmet@example.com) |
INSERT … 'Ayşe Demir' | 1 | (1, Ahmet Yılmaz, ahmet@example.com) (2, Ayşe Demir, ayse@example.com) |
UPDATE … WHERE id = 1 | 1 | (1, Mehmet Akdeniz, ahmet@example.com) (2, Ayşe Demir, ayse@example.com) |
DELETE … WHERE id = 1 | 1 | (2, Ayşe Demir, ayse@example.com) |
SELECT * FROM users | — | unchanged; result: (2, Ayşe Demir, ayse@example.com) |
name changed), and after the delete (right; the row with number 1 is struck through).An update changes only the column named in SET; email stays the same (Figure 11.8). WHERE id = 1 selects only the first row. The delete uses the same condition and removes only the first row. The final SELECT does not change the table; it only reads and returns one row. The deleted number 1 is not passed to Ayşe: her id stays 2. A primary key does not change once it has been assigned.
Forgetting WHERE in UPDATE or DELETE. UPDATE users SET name = 'X' raises no error; it changes the name of every row in the table. DELETE FROM users deletes all rows but leaves the table itself. On a table with three rows, both statements return 3. The database does not treat this as an error; the only ways to undo it are to work inside a transaction or to restore a backup.
11.3.4SELECT: filtering, sorting, limiting
SELECT is the most used and richest statement in SQL. The examples in this section work with a score table of five rows (Figure 11.9).
scores table.A query consists of at most seven clauses; five of them are used here. SELECT says which columns to return, and FROM says which table to read. WHERE filters rows by a condition. The condition can use comparisons such as =, <> (not equal), <, and >=, and the connectives AND and OR. LIKE 'e%' means "starts with e": % stands for any number of characters and _ for exactly one. ORDER BY sorts the result; DESC means descending, and the default ASC means ascending. LIMIT n takes the first n rows. Table 11.6 gives four queries and their results.
| Query | Result |
|---|---|
SELECT player, score FROM scores WHERE score < 90 ORDER BY score DESC | naz 81, ada 72, ece 58 |
SELECT player, score FROM scores ORDER BY score DESC, player LIMIT 3 | can 95, efe 95, naz 81 |
SELECT player, score FROM scores WHERE player LIKE 'e%' | ece 58, efe 95 |
SELECT COUNT(*), AVG(score), MAX(score) FROM scores WHERE score >= 60 | 4 · 85.75 · 95 |
The first query selects scores below 90; can and efe (95) are dropped. The remaining three rows are sorted by score in descending order. The second query has no filter. Its sort has two keys: score descending first, and player name ascending when scores tie. can and efe tie at 95; can comes first alphabetically. LIMIT 3 takes the first three rows. Without the second key, the order of tied scores would be undefined, and the result would depend on how the DBMS happened to lay out the data.
The third query returns the two names that start with e. In SQLite, LIKE is case-insensitive for ASCII letters; LIKE 'E%' gives the same two rows. The fourth query returns a single row, because COUNT, AVG, and MAX are aggregate functions: each produces one value from a set of rows. There are four scores of 60 or more: 72, 95, 95, and 81. Their sum is 343 and their average is 343 / 4 = 85.75. The maximum is 95. SUM and MIN belong to the same family.
Keep in mind how these functions behave on an empty set. With WHERE score > 100, where no row is selected, COUNT(*) returns 0, while AVG(score) and SUM(score) return NULL. The query still returns a single row; its values are empty.
11.3.5Code trace: a SELECT query
An SQL statement does not run in the order it is written. The following Java code sends a query to the database and prints the result row by row. What matters here is not the JDBC types but the stages the query goes through.
String sql = "SELECT player, score FROM scores "
+ "WHERE score > 70 "
+ "ORDER BY player DESC LIMIT 2";
try (Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(sql)) {
while (rs.next()) {
System.out.println(rs.getString("player") + " "
+ rs.getInt("score"));
}
}naz 81
efe 95The database processes FROM first: it takes the five rows of the table. Then it applies the condition WHERE score > 70 to each row and drops ece (58); four rows remain. Next, ORDER BY player DESC sorts the rows in reverse alphabetical order by name: naz, efe, can, ada. The sort is by name, not by score. Finally LIMIT 2 takes the first two rows. The result set has two rows: (naz, 81) and (efe, 95). Figure 11.10 shows these stages.
WHERE drops ece (left), ORDER BY sorts the names in reverse order (middle), and LIMIT 2 makes the first two rows the result set (right).The result reaches Java as a ResultSet object. This object has a cursor, which starts out before the first row. Each call to rs.next() advances the cursor by one row; it returns true if there is a row and false if there are none left. That is why the loop has the form while (rs.next()): the first call moves the cursor to the first row, and the body reads that row's columns. Table 11.7 gives the ten steps.
| Step | Line | Variables | New output |
|---|---|---|---|
| 1 | 1: String sql = "SELECT player, score FROM scores "2: + "WHERE score > 70 "3: + "ORDER BY player DESC LIMIT 2"; | sql=SELECT … LIMIT 2 | — |
| 2 | 5: ResultSet rs = st.executeQuery(sql)) { | stage=FROM | — |
| 3 | 5: ResultSet rs = st.executeQuery(sql)) { | stage=WHERE | — |
| 4 | 5: ResultSet rs = st.executeQuery(sql)) { | stage=ORDER BY | — |
| 5 | 5: ResultSet rs = st.executeQuery(sql)) { | stage=LIMIT | — |
| 6 | 6: while (rs.next()) { | rs.next()=true | — |
| 7 | 7: System.out.println(rs.getString("player") + " "8: + rs.getInt("score")); | player=naz, score=81 | naz 81 |
| 8 | 6: while (rs.next()) { | rs.next()=true | — |
| 9 | 7: System.out.println(rs.getString("player") + " "8: + rs.getInt("score")); | player=efe, score=95 | efe 95 |
| 10 | 6: while (rs.next()) {10: } | rs.next()=false | — |
The logical order of execution is visible in this example: FROM → WHERE → ORDER BY → LIMIT. The column selection in SELECT happens near the end. This order matters even more in grouping queries. To predict what a query will return, read it in this order rather than in the order it is written.
On the scores table, what do the queries SELECT player FROM scores WHERE score > 90 OR player = 'ece' and SELECT player FROM scores LIMIT 2 OFFSET 1 return?
In the first, the condition is evaluated separately for each row. can and efe, with 95, satisfy the first part; ece satisfies the second. ada (72) and naz (81) satisfy neither. The result is can, ece, efe. Because no sort was requested, SQLite returns the rows in insertion order. In the second, OFFSET 1 skips the first row and LIMIT 2 takes the next two: can, ece. The queries gave these results when run. Without ORDER BY, the standard does not guarantee row order; if the order matters, always write ORDER BY.
11.4Relationships and grouping
In a real application the data does not fit in a single table. Students, departments, courses, and orders live in separate tables and are linked to one another. This section explains why tables are split, how they are linked, and how linked tables are combined in a single query.
11.4.1Normalization
Suppose a shop keeps its orders in a single table: each row holds the customer's name, phone, and the product ordered. If Ali places three orders, his name and phone are repeated in three rows (Figure 11.11, top). This repetition is not just wasted space; the real problem is the risk of inconsistency.
customers and orders. Orders link to a customer through customer_id.Repetition leads to three kinds of corruption, called anomalies. Update anomaly: when Ali's phone changes, every row must be corrected separately; if one is forgotten, Ali has two different phones and there is no way to know which is right. Insert anomaly: a customer who has no orders yet cannot be recorded, because every row is an order. Delete anomaly: when Ece's only order is deleted, Ece's phone is lost too.
Normalization is splitting data into tables so that each fact is stored in exactly one place, in order to avoid repetition. The split tables are linked to one another by a key.
In the lower part of the figure, the customer's information is stored once in the customers table. The orders table holds not the customer's name and phone but only the customer's number (customer_id). When Ali's phone changes, a single cell is updated. A customer with no orders can be added to customers. Even if Ece's order is deleted, Ece's record remains. All three anomalies disappear at once.
The first rule of normalization is called first normal form: each cell holds a single value. A customer's two phones are not written as a list in one cell such as '555-11, 555-33'. In such a cell, searching for "the customer whose phone is 555-33" becomes hard, and removing one number turns into text processing. The phones are moved either to separate rows or to a separate phones(customer_id, number) table. Higher normal forms exist as well; for this course the first rule and the principle "each fact in one place" are enough.
11.4.2Foreign keys
The column that links split tables has a special name.
A foreign key is a column that points to another table's primary key. The value of a foreign key either equals the key of a row in that table or is NULL.
The chapter's relationship examples use two tables: depts and students. Every student has a department, and the link is made through the dept_id column:
CREATE TABLE depts (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL);
CREATE TABLE students (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
dept_id INTEGER REFERENCES depts(id));REFERENCES depts(id) declares that dept_id is a foreign key. The following rows are inserted into the tables; Deniz's department is not yet known:
INSERT INTO depts(name) VALUES ('CS'), ('EE'), ('ME');
INSERT INTO students(name, dept_id)
VALUES ('Ada', 1), ('Bora', 2), ('Cem', 1), ('Deniz', NULL);students.dept_id column points to the depts.id column. A department can have many students: a one-to-many relationship. Deniz has no department; his dept_id is NULL.Figure 11.12 shows the relationship. Ada and Cem both have dept_id 1; both are in the CS department. A department can have several students, but a student has only one department. This structure is called a one-to-many relationship. In Java the counterpart is that each Student object holds a Dept reference. In the table, a key value stands in place of the object reference.
The main benefit of a foreign key is integrity checking. Adding a student to the nonexistent department 9, or deleting a department that still has students, breaks the link: the student carries a number that points nowhere. A DBMS rejects both operations. SQLite, however, does not perform this check by default, for backward compatibility. The check must be enabled separately on every connection:
PRAGMA foreign_keys = ON;
INSERT INTO students(name, dept_id) VALUES ('Efe', 9); -- rejected
DELETE FROM depts WHERE id = 2; -- rejected: Bora is linked
DELETE FROM depts WHERE id = 3; -- accepted: ME is emptyWhen the same operations are run first with the default setting and then with the check enabled, the following output is obtained:
== no PRAGMA (default)
foreign_keys = 0
accepted (1): INSERT INTO students(name, dept_id) VALUES ('Efe', 9)
accepted (1): DELETE FROM depts WHERE id = 2
== PRAGMA foreign_keys = ON
rejected: INSERT INTO students(name, dept_id) VALUES ('Efe', 9) -> [SQLITE_CONSTRAINT_FOREIGNKEY] A foreign key constraint failed (FOREIGN KEY constraint failed)
rejected: DELETE FROM depts WHERE id = 2 -> [SQLITE_CONSTRAINT_FOREIGNKEY] A foreign key constraint failed (FOREIGN KEY constraint failed)
accepted (1): DELETE FROM depts WHERE id = 3
accepted (1): INSERT INTO students(name, dept_id) VALUES ('Nil', NULL)With the default setting, PRAGMA foreign_keys is 0. The insert into department 9 is silently accepted; Bora's department is deleted too, and Bora's dept_id now points to a row that no longer exists. With the check enabled, both operations are rejected with FOREIGN KEY constraint failed. The ME department, which has no students, can be deleted. A NULL foreign key is always accepted, because it means "no department". In Java this setting is made right after the connection is opened, with stmt.execute("PRAGMA foreign_keys = ON"). The setting is specific to the connection: it must be repeated on every new connection.
Another kind of relationship besides one-to-many is also common: many-to-many. A student is enrolled in many courses, and a course has many students. This relationship cannot be built with columns of the two tables alone; a third, linking table is needed:
CREATE TABLE enrollments (
student_id INTEGER REFERENCES students(id),
course_id INTEGER REFERENCES courses(id),
PRIMARY KEY (student_id, course_id));Each row of the enrollments table says "this student is enrolled in this course". Each of the two columns is a foreign key to a different table. The primary key is the combination of the two columns, so the same student cannot be enrolled in the same course twice.
11.4.3Combining tables with JOIN
Normalization has a price: the answer to "Which department is Ada in?" is now spread over two tables. students holds only the number 1, and depts says that 1 is "CS". To bring the two pieces of information together in one result, the tables are joined.
A join (JOIN) is an SQL operation that matches the rows of two tables according to an ON condition and produces a single result table. A plain JOIN (or INNER JOIN) returns only the rows that have a match; a LEFT JOIN returns all rows of the left table.
SELECT s.name AS student, d.name AS dept
FROM students s JOIN depts d
ON s.dept_id = d.id
ORDER BY s.idIn the query, s and d are table aliases: FROM students s says that s can be written in place of students in the rest of the query. Aliases are required here, because both tables have a column called name. s.name is the student's name and d.name is the department's name. AS gives a result column a new name; on the Java side the column is read by that name: rs.getString("dept"). ON s.dept_id = d.id is the matching condition: a student row is matched with the department row whose id equals its own dept_id.
Written with LEFT JOIN on the same tables, the query becomes:
SELECT s.name AS student, d.name AS dept
FROM students s LEFT JOIN depts d
ON s.dept_id = d.id
ORDER BY s.idThe results of the two queries are side by side in Table 11.8. The only difference is Deniz. Because Deniz's dept_id is NULL, he matches no department. JOIN leaves a row without a match out of the result. LEFT JOIN keeps every row of the left table (students); if there is no match, it fills the right table's columns with NULL. In Java, reading this value with getString gives null.
student | JOIN (INNER) | LEFT JOIN |
|---|---|---|
| Ada | CS | CS |
| Bora | EE | EE |
| Cem | CS | CS |
| Deniz | no row | NULL |
Which one to choose depends on the question. To "list the students who have a department, with the department name", use JOIN; to "list all students, and write the department name where there is one", use LEFT JOIN. The order of the tables matters in LEFT JOIN: if you write depts d LEFT JOIN students s, the preserved side is the departments. That query returns the ME department with a NULL student.
Two mistakes are common. The first is writing SELECT name without an alias. SQLite cannot tell which name is meant and rejects the query with the message ambiguous column name: name. The second is forgetting the ON condition:
SELECT COUNT(*) FROM students, depts -- 12In a join without a condition, every row is matched with every row. Four students and three departments give 4 × 3 = 12 rows. This is called a Cartesian product. The result is meaningless: Ada appears in the CS, EE, and ME departments at once. With large tables this mistake is very expensive: 10,000 students and 100 departments produce a million rows.
11.4.4Code trace: a JOIN query
The following code runs the join query from Java. stmt is a Statement created on an open connection.
String sql = "SELECT s.name AS student, d.name AS dept "
+ "FROM students s JOIN depts d "
+ "ON s.dept_id = d.id ORDER BY s.id";
try (ResultSet rs = stmt.executeQuery(sql)) {
while (rs.next()) {
System.out.println(rs.getString("student") + " - "
+ rs.getString("dept"));
}
}Ada - CS
Bora - EE
Cem - CSFor each row of students, the database looks in depts for the row whose id matches. Ada's dept_id is 1; department 1 is CS. Bora links to 2, that is, EE. Cem links to 1 again; the same department row is used a second time. CS is written once in the department table but appears twice in the result. Deniz's dept_id is NULL, and NULL is not considered equal to any id; Deniz does not enter the result (Figure 11.13).
NULL department matches no row (left); the result set has three rows (right).| Step | Line | Variables | New output |
|---|---|---|---|
| 1 | 1: String sql = "SELECT s.name AS student, d.name AS dept "2: + "FROM students s JOIN depts d "3: + "ON s.dept_id = d.id ORDER BY s.id"; | — | — |
| 2 | 4: try (ResultSet rs = stmt.executeQuery(sql)) { | — | — |
| 3 | 4: try (ResultSet rs = stmt.executeQuery(sql)) { | — | — |
| 4 | 4: try (ResultSet rs = stmt.executeQuery(sql)) { | — | — |
| 5 | 4: try (ResultSet rs = stmt.executeQuery(sql)) { | — | — |
| 6 | 5: while (rs.next()) {6: System.out.println(rs.getString("student") + " - "7: + rs.getString("dept")); | row=1 | Ada - CS |
| 7 | 5: while (rs.next()) {6: System.out.println(rs.getString("student") + " - "7: + rs.getString("dept")); | row=2 | Bora - EE |
| 8 | 5: while (rs.next()) {6: System.out.println(rs.getString("student") + " - "7: + rs.getString("dept")); | row=3 | Cem - CS |
| 9 | 5: while (rs.next()) {9: } | row=none | — |
The Java side is the same as in the previous example: the cursor advances row by row through the result set. The columns are read by the names given with AS: "student" and "dept". If rs.getString("name") had been written, the driver would raise an error, because the result has no column called name. With LEFT JOIN, Deniz - null would appear as a fourth line; this was verified by running it.
11.4.5GROUP BY and HAVING
Aggregate functions give a single value when applied to a whole table. Often, though, you want a separate value for each group: the number of orders per customer, the number of students per department. The examples in this section use an order table of six rows:
INSERT INTO orders(customer, amount) VALUES
('Ali', 120), ('Ece', 80), ('Ali', 50),
('Can', 200), ('Ali', 30), ('Ece', 40);GROUP BY customer gathers the rows that have the same customer value into one group. Aggregate functions are computed separately for each group, and each group becomes a single row in the result (Figure 11.14). Ali has three orders: 120 + 50 + 30 = 200. Can has a single order of 200, and Ece has two orders: 80 + 40 = 120.
orders table is split into three groups by customer; the count and the total are computed for each group.Filtering can happen before or after grouping. WHERE filters rows before grouping. HAVING filters groups after grouping. That is why a condition containing an aggregate function cannot go in WHERE: when WHERE runs there are no groups yet, and therefore no SUM(amount). If you write WHERE SUM(amount) >= 150, SQLite rejects it with the message misuse of aggregate: SUM(). Table 11.10 compares three cases.
| Rest of the query | Result |
|---|---|
GROUP BY customer | Ali (3, 200) · Can (1, 200) · Ece (2, 120) |
WHERE amount >= 50 GROUP BY customer | Ali (2, 170) · Can (1, 200) · Ece (1, 80) |
GROUP BY customer HAVING SUM(amount) >= 150 | Ali (3, 200) · Can (1, 200) |
In the second row, WHERE amount >= 50 first filters the individual orders: Ali's order of 30 and Ece's order of 40 are dropped. The groups are built from the remaining orders. Ali's count falls to 2 and his total to 170. In the third row, all orders are grouped first, and then Ece's group, whose total is below 150, is dropped. The two queries look alike but answer different questions: one says "count the orders of 50 TL or more by customer", the other "find the customers whose total is 150 or more".
The clauses of a query run logically in this order:
FROM → WHERE → GROUP BY → HAVING → SELECT → ORDER BY → LIMIT
This order explains many rules. WHERE cannot use aggregate functions, because it comes before grouping. ORDER BY can use aliases defined in SELECT, because it comes after it.
Grouping is also used together with joins. The number of students in each department is found like this:
SELECT d.name, COUNT(s.id)
FROM depts d LEFT JOIN students s
ON s.dept_id = d.id
GROUP BY d.idThe result is CS 2 · EE 1 · ME 0. Two details matter here. Thanks to LEFT JOIN, ME, which has no students, also appears in the result; a plain JOIN would have hidden it. The second detail is COUNT(s.id). COUNT(column) counts only values that are not NULL. In ME's single joined row, s.id is NULL and is not counted; the result is 0. COUNT(*), on the other hand, counts rows. Had it been used, it would have given ME a 1; this was verified by running it.
There is one more trap in grouping. In the query SELECT customer, amount FROM orders GROUP BY customer, amount is neither grouped nor inside an aggregate function. Ali's group has three different amounts; which one should be shown? SQLite raises no error and returns the value from one of the rows in the group. In a test, Ali came out as 120, Can as 200, and Ece as 80. Many databases, such as PostgreSQL and SQL Server, reject this query. The rule is simple: every column in SELECT either appears in GROUP BY or is inside an aggregate function.
11.4.6Code trace: a GROUP BY query
The following code combines grouping, group filtering, and a two-key sort in a single query:
String sql = "SELECT customer, COUNT(*) AS num, "
+ "SUM(amount) AS total FROM orders "
+ "GROUP BY customer HAVING SUM(amount) >= 150 "
+ "ORDER BY total DESC, customer";
try (ResultSet rs = stmt.executeQuery(sql)) {
while (rs.next()) {
System.out.println(rs.getString("customer") + ": "
+ rs.getInt("num") + " orders, "
+ rs.getInt("total") + " TL");
}
}Ali: 3 orders, 200 TL
Can: 1 orders, 200 TLThe database first splits the six rows into three groups by customer. For each group it computes COUNT(*) and SUM(amount): Ali 3 and 200, Can 1 and 200, Ece 2 and 120. HAVING SUM(amount) >= 150 drops Ece's group. ORDER BY total DESC, customer sorts the remaining two groups by total in descending order. Ali and Can tie at 200; since the second key is the name, Ali comes first (Figure 11.15).
HAVING drops Ece (middle), the sorted result (right).| Step | Line | Variables | New output |
|---|---|---|---|
| 1 | 1: String sql = "SELECT customer, COUNT(*) AS num, "2: + "SUM(amount) AS total FROM orders "3: + "GROUP BY customer HAVING SUM(amount) >= 150 "4: + "ORDER BY total DESC, customer"; | — | — |
| 2 | 5: try (ResultSet rs = stmt.executeQuery(sql)) { | — | — |
| 3 | 5: try (ResultSet rs = stmt.executeQuery(sql)) { | — | — |
| 4 | 5: try (ResultSet rs = stmt.executeQuery(sql)) { | — | — |
| 5 | 5: try (ResultSet rs = stmt.executeQuery(sql)) { | — | — |
| 6 | 6: while (rs.next()) {7: System.out.println(rs.getString("customer") + ": "8: + rs.getInt("num") + " orders, "9: + rs.getInt("total") + " TL"); | row=1 | Ali: 3 orders, 200 TL |
| 7 | 6: while (rs.next()) {7: System.out.println(rs.getString("customer") + ": "8: + rs.getInt("num") + " orders, "9: + rs.getInt("total") + " TL"); | row=2 | Can: 1 orders, 200 TL |
| 8 | 6: while (rs.next()) {11: } | row=none | — |
On the Java side, the aliases (num, total) are read like column names: rs.getInt("num"). The result has one row per group; the individual orders are not visible. Ali's three orders have become a single line, "Ali: 3 orders, 200 TL".
11.4.7NULL: the absence of a value
Deniz's department is unknown. This is shown in the table as NULL.
In SQL, NULL is a special marker that means a value is unknown or absent. NULL is neither 0 nor the empty string (''). Every comparison involving NULL gives the result "unknown".
SQL uses a three-valued logic: true, false, and unknown. The comparison dept_id = NULL is not true even for Deniz; it is unknown. Whether an unknown value equals another unknown value is unknown as well. WHERE selects only the rows whose condition is true; that is why the first query below returns no rows:
SELECT name FROM students WHERE dept_id = NULL; -- 0 rows
SELECT name FROM students WHERE dept_id IS NULL; -- Deniz
SELECT name FROM students WHERE dept_id <> 1; -- only Bora
SELECT name, COALESCE(dept_id, 0) FROM students; -- Deniz 0
SELECT COUNT(*), COUNT(dept_id) FROM students; -- 4 and 3The correct forms are IS NULL and IS NOT NULL. The result of the third line is more surprising. dept_id <> 1 does not select Deniz either, because it is not even known whether NULL differs from 1. If you want "the students outside CS", write WHERE dept_id <> 1 OR dept_id IS NULL.
NULL also propagates through arithmetic: the result of NULL + 1 is NULL. COALESCE(dept_id, 0) returns the second argument if the first is NULL; this puts 0 in place of NULL. Aggregate functions skip NULLs. COUNT(*) counts rows and gives 4; COUNT(dept_id) counts the values that are not NULL and gives 3. If no rows match, AVG and SUM return NULL and COUNT returns 0. All of these lines were verified by running them in a Java program.
There is a problem on the Java side as well. Primitive types such as int cannot be null. rs.getInt returns 0 for a NULL column. But is the 0 really 0, or was it NULL? To tell the difference, call wasNull() right after the read:
String sql = "SELECT name, dept_id FROM students "
+ "WHERE id >= 3";
try (ResultSet rs = stmt.executeQuery(sql)) {
while (rs.next()) {
int d = rs.getInt("dept_id");
boolean none = rs.wasNull();
System.out.println(rs.getString("name") + " " + d
+ (none ? " (NULL)" : ""));
}
}Cem 1
Deniz 0 (NULL)
== late wasNull
Cem 1
Deniz 0
getString: null, getObject: null
SELECT name FROM students WHERE dept_id = NULL
-> 0 rows:
SELECT name FROM students WHERE dept_id IS NULL
-> 1 rows: Deniz;
SELECT name FROM students WHERE dept_id IS NOT NULL
-> 3 rows: Ada; Bora; Cem;
SELECT name FROM students WHERE dept_id <> 1
-> 1 rows: Bora;
SELECT NULL + 1, NULL = NULL, NULL IS NULL, COALESCE(NULL, 0)
-> 1 rows: null null 1 0;
SELECT name, COALESCE(dept_id, 0) FROM students
-> 4 rows: Ada 1; Bora 2; Cem 1; Deniz 0;
SELECT COUNT(*), COUNT(dept_id) FROM students
-> 1 rows: 4 3;
SELECT AVG(dept_id), SUM(dept_id) FROM students WHERE id > 10
-> 1 rows: null null;
SELECT AVG(dept_id), SUM(dept_id) FROM students
-> 1 rows: 1.33333333333333 4;
SELECT name FROM students WHERE NOT (dept_id = 1)
-> 1 rows: Bora; The first two lines of the output come from the program above. Cem's department is 1, and wasNull() returns false. For Deniz, getInt gives 0, wasNull() returns true, and "(NULL)" is appended to the line. wasNull() looks only at the last column read. In the second experiment, labeled "late wasNull", getString("name") is read after dept_id, and wasNull() is called after that. This time the name is what was asked about; since the name is not NULL, "(NULL)" is not written on Deniz's line. getString and getObject, on the other hand, return Java's own null directly for NULL; wasNull() is not needed with these methods. The remaining lines of the output are the actual results of the SQL queries above.
Writing WHERE dept_id = NULL. The query raises no error; it just returns no rows, and the program concludes that "there are no students without a department". A check for NULL is always written with IS NULL. The Java counterpart is similar: getInt returning 0 does not show that the value is 0; wasNull() is called right after the relevant getInt.
11.4.8Indexes
The secret of a database's fast search is the index.
A database index is an additional structure that keeps the values of a column in sorted order and points to the row where each value is found. SQLite stores an index as a B-tree.
An index is like the index at the back of a book. The pages where the word "inheritance" appears can be found from the index without reading the book from cover to cover. Without an index, the query WHERE name = 'Cem' looks at every row of the table; this is called a scan. With an index, a search similar to binary search is made in the sorted structure, and the database goes directly to Cem's row (Figure 11.16). In a table of n rows, a scan needs n comparisons, while a search in the B-tree takes about log n steps. For a million rows, that is the difference between a million and about twenty.
An index is created with CREATE INDEX. SQLite's EXPLAIN QUERY PLAN statement shows how a query will be executed, that is, whether the table will be scanned or an index will be used:
CREATE INDEX idx_stu_name ON students(name);
EXPLAIN QUERY PLAN
SELECT * FROM students WHERE name = 'Cem';Table 11.12 gives the plans for four cases. The plans were obtained with SQLite 3.40.0.
| Case | EXPLAIN QUERY PLAN output |
|---|---|
Without an index, WHERE name = 'Cem' | SCAN students |
With an index, WHERE name = 'Cem' | SEARCH students USING INDEX idx_stu_name (name=?) |
WHERE id = 3 | SEARCH students USING INTEGER PRIMARY KEY (rowid=?) |
WHERE name LIKE '%em' | SCAN students |
SCAN shows that the table will be scanned, and SEARCH that an index will be used for the search. No separate index is needed for a primary key; INTEGER PRIMARY KEY is already the table's own ordering key. The index of a UNIQUE column is created automatically too, because the DBMS needs it to check for duplicates.
The last row shows the limit of an index. LIKE '%em' means "ends with em". An index keeps names sorted from the beginning; names that end in "em" are scattered throughout the sequence. A leading wildcard therefore cannot use the index. In the test, LIKE 'C%' also produced a SCAN. In SQLite LIKE is case-insensitive, while an ordinary index is case-sensitive, so even a prefix search did not use the index with default settings.
An index has a cost. Every INSERT, UPDATE, and DELETE updates not only the table but also the index, and the index takes up disk space. That is why not every column gets an index. An index goes on columns that are searched often and used in WHERE, JOIN, or ORDER BY. To see how large the effect is, 200 searches by the name column were run on a table of 200,000 rows. Without an index the searches took 633 ms; after the index was created, the same searches took 1 ms. The times vary with the machine and the run; the ratio is hundreds of times each time.
11.5JDBC
SQL statements are the database's language; the Java program must pass these statements to the database and get the results back. JDBC builds this bridge.
11.5.1What is JDBC?
JDBC (Java Database Connectivity) is the standard API (application programming interface) that Java offers for connecting to databases. It lives in the java.sql package and ships with the JDK. The code that talks to a particular database is supplied by that database's JDBC driver.
The structure of JDBC is a fine application of the interface concept from object-oriented programming. Connection, Statement, and ResultSet in the java.sql package are interfaces; they only say which methods will exist. The driver of each database vendor implements these interfaces with its own classes. The SQLite driver knows how to talk to a SQLite file, and the MySQL driver knows how to talk to a MySQL server (Figure 11.17).
DriverManager picks the right driver; the driver connects to a SQLite file or a MySQL server.Because the program knows only the interfaces, switching databases often means changing only the driver jar and the connection URL. Polymorphism is at work here. The type of the variable in the program is Connection. At run time, the class of the actual object the variable refers to is org.sqlite.jdbc4.JDBC4Connection in the SQLite driver. This name was verified by printing conn.getClass().getName(). When the program calls conn.createStatement(), the JVM runs this class's implementation of the Connection interface. The same line runs the MySQL driver's implementation with MySQL.
An object of an interface cannot be created directly. If you write new Connection(), the compiler rejects it:
Main.java:4: error: Connection is abstract; cannot be instantiated
Connection conn = new Connection();
^
1 errorIt is possible to build the connection object with new from the driver's class, but that would be wrong, because the program would become dependent on one driver. A connection is always obtained with DriverManager.getConnection; the driver decides which class's object is returned.
11.5.2The core JDBC types
A JDBC program is written with a few types. Table 11.13 lists them and their important methods.
| Type | Purpose | Important methods |
|---|---|---|
DriverManager | Finds the right driver and opens a connection | getConnection(url), getConnection(url, user, password) |
Connection | An open session with the database | createStatement(), prepareStatement(sql), commit(), rollback(), close() |
Statement | Runs a fixed SQL text | execute, executeUpdate, executeQuery |
PreparedStatement | Pre-compiled SQL with ? placeholders | setInt, setString, executeUpdate(), executeQuery() |
ResultSet | The rows of a query result and a cursor | next(), getInt("id"), getString("name") |
SQLException | A database error; a checked exception | getMessage(), getErrorCode() |
The types form a chain. DriverManager gives a Connection. The Connection produces a Statement or a PreparedStatement. When that object runs a query, a ResultSet comes back. Each link is obtained from the one before it; the programmer calls only DriverManager directly.
To use these types, write import java.sql.*; at the top of the file. If it is forgotten, the compiler cannot find the types:
Main.java:3: error: cannot find symbol
Connection conn = DriverManager.getConnection("jdbc:sqlite:sample.db");
^
symbol: class Connection
location: class Main
Main.java:3: error: cannot find symbol
Connection conn = DriverManager.getConnection("jdbc:sqlite:sample.db");
^
symbol: variable DriverManager
location: class Main
2 errorsSQLException is a checked exception. Almost all JDBC methods declare that they may throw it. JDBC code therefore either sits inside a try-catch or the method declares throws SQLException. If neither is done, the program does not compile:
Main.java:4: error: unreported exception SQLException; must be caught or declared to be thrown
Connection conn = DriverManager.getConnection("jdbc:sqlite:sample.db");
^
1 errorConnection, Statement, and ResultSet hold resources in the database: an open file, locks, memory. All three implement the AutoCloseable interface and must be closed when you are done with them. The safest way is try-with-resources.
11.5.3The connection URL
DriverManager learns which database to connect to from a text address. This address is called the JDBC URL (Figure 11.18).
jdbc), the subprotocol (selects the driver), and the file or address of the database.The format of the URL is jdbc:<subprotocol>:<database file or address>. The first part is always jdbc. The second part determines the driver: sqlite, mysql, postgresql. DriverManager asks the registered drivers in turn whether they accept the URL. The first driver that accepts it opens the connection. The format of the third part is specific to the driver. Table 11.14 gives examples.
| Connection URL | Meaning |
|---|---|
jdbc:sqlite:sample.db | sample.db in the working folder; created empty if it does not exist |
jdbc:sqlite:C:/data/school.db | A file given by its full path |
jdbc:sqlite::memory: | A temporary in-memory database; deleted when the connection closes |
jdbc:mysql://localhost:3306/testdb | A MySQL server: machine, port, database name; a user name and password are also needed |
An in-memory database is very handy for experiments: it leaves no file on disk and starts clean on every run. Many examples in this chapter were run with jdbc:sqlite::memory:. However, an in-memory database belongs to its connection. A table created in one connection does not exist in a second connection opened with the same URL. In the test, the second connection got the message no such table: t.
A relative file path is resolved against the working folder. In Eclipse the working folder is the project folder; on the command line it is the folder from which the java command was given. So if a program is run from two places, two separate sample.db files can appear. SQLite creates a file that does not exist but does not create a folder that does not exist. With the URL jdbc:sqlite:sub/folder/school.db, if the folder sub does not exist, the connection fails with the message "path … does not exist".
In older books and code, the following line appears before the connection: Class.forName("org.sqlite.JDBC");. This line loaded the driver class and had it register itself with DriverManager. Since JDBC 4.0 (Java 6), the driver is loaded automatically from the jar on the classpath, and the line is no longer needed. Writing it does no harm. What happens if the driver is not on the classpath? When the program was run without the driver jar, this output was obtained:
No suitable driver found for jdbc:sqlite:sample.db
ClassNotFoundException: org.sqlite.JDBCThe first line is the message of the SQLException thrown by getConnection: no driver that accepts the URL was found. The same message appears when the URL has a typo. For example, the URL jdbc:sqlit:school.db gives this message even when the driver is loaded, because no driver recognizes the subprotocol sqlit. The second line is the ClassNotFoundException received when the old method looks up the driver class.
11.5.4The steps of a JDBC program
Every JDBC program follows the same five steps (Figure 11.19): open a connection, create a statement object, run the SQL, process the result, and close the resources.
try (Connection conn = DriverManager.getConnection(url); // 1
Statement stmt = conn.createStatement(); // 2
ResultSet rs = stmt.executeQuery(sql)) { // 3
while (rs.next()) { // 4
System.out.println(rs.getInt(1));
}
} // 5: rs, stmt, conn auto-closed in reverseThe structure of the code matches the steps one to one. Steps one, two, and three happen in order in the try-with-resources parentheses: the connection is opened, a Statement is taken from it, and the Statement runs the query and returns a ResultSet. Step four is the while (rs.next()) loop. No code is written for step five: when the block ends, even after an error, the resources are closed in the reverse order of opening. First rs, then stmt, and last conn.
The reverse order is not arbitrary. A ResultSet depends on its Statement, and the Statement depends on its Connection. If the connection were closed first, the others would be left dangling. To verify the closing, the resources were copied into variables outside the block and queried with isClosed() after the block ended:
7
8
true true true
The database has been closedAll three resources are closed (true true true). An attempt to run a query on the closed Statement threw a SQLException; its message is on the last line. Connections that are not closed can leave the SQLite file locked. Another program, or even another connection of the same program, cannot write to the file. In long-running programs, objects that are not closed also cause memory leaks.
The code has one more detail: rs.getInt(1). Columns can be read by name or by position. In JDBC, column numbers start at 1. For a programmer used to Java arrays starting at 0, this is a frequent source of errors.
Trying to use a try-with-resources resource outside the block. The scope of a variable declared in the parentheses is the block only; when the block ends, the resource is both closed and out of sight. The compiler rejects the use outside:
Main.java:6: error: cannot find symbol
conn.close();
^
symbol: variable conn
location: class Main
1 error11.6Basic operations
The six small programs in this section run in sequence on the same file, sample.db: connecting, creating a table, inserting, reading, updating, and deleting. The programs are independent; each opens and closes its own connection. The data stays persistently in the file between programs. Each program was run in full inside public static void main with import java.sql.*;; the chapter shows only the body of main.
11.6.1Connecting to SQLite
// Path to the database file (connection URL)
String url = "jdbc:sqlite:sample.db";
try (Connection conn = DriverManager.getConnection(url)) {
// Print a message if connected.
if (conn != null) {
System.out.println("Connected!");
}
} catch (SQLException e) {
// Print the error message on failure.
System.out.println(e.getMessage());
}Connected!The program keeps the connection URL in a variable and opens the connection with getConnection. If the file does not exist, SQLite creates it; sample.db, which did not exist before the first run, is on disk after it. One interesting detail: the size of the created file is 0 bytes. SQLite writes no content to the file until the first table is written. This was seen by asking a File object about the file's existence and size.
The if (conn != null) check is only an extra safeguard. If getConnection fails, it does not return null; it throws SQLException. So if execution reaches the inside of the try block, the connection is certainly open. The catch block prints the error message; if the driver were not on the classpath, it would print "No suitable driver found …" here.
11.6.2Creating a table
String url = "jdbc:sqlite:sample.db";
String sql = "CREATE TABLE IF NOT EXISTS users "
+ "(id INTEGER PRIMARY KEY, name TEXT, email TEXT)";
try (Connection conn = DriverManager.getConnection(url);
Statement stmt = conn.createStatement()) {
// Create the table.
stmt.execute(sql);
System.out.println("Table created!");
} catch (SQLException e) {
System.out.println(e.getMessage());
}Table created!This time there are two resources in the try-with-resources parentheses: the connection and a Statement. Resources inside the parentheses are separated by semicolons. execute(sql) runs any kind of SQL. Its return value says whether the statement produced a result set. CREATE TABLE produces no result set; execute returns false. For SELECT it would return true. The program does not use the return value; both cases were verified by printing them in a separate experiment.
Thanks to IF NOT EXISTS, the program raises no error when it is run a second time. Without this clause, the second run would give this message: [SQLITE_ERROR] SQL error or missing database (table users already exists).
11.6.3Inserting data
String url = "jdbc:sqlite:sample.db";
String sql = "INSERT INTO users(name, email) "
+ "VALUES('Ahmet Yılmaz', 'ahmet@example.com')";
try (Connection conn = DriverManager.getConnection(url);
Statement stmt = conn.createStatement()) {
// Insert data into the database.
int n = stmt.executeUpdate(sql);
System.out.println("Data inserted! (" + n + " row)");
} catch (SQLException e) {
System.out.println(e.getMessage());
}Data inserted! (1 row)The insert is done with executeUpdate. This method is used for INSERT, UPDATE, and DELETE and returns the number of rows the statement affected, as an int. Since a single row was inserted, the returned value is 1. No id was given; SQLite assigns 1 because the table is empty.
The SQL text is written in Java as two pieces joined with +. Note the space at the end of the first piece: "INSERT INTO users(name, email) ". If the space were forgotten, the text would join as …email)VALUES(…. SQLite would accept that, but elsewhere, for example in "FROM users" + "WHERE id = 1", usersWHERE appears and the query breaks. Text values are in single quotes, as SQL requires.
Each time the program runs, a new row is inserted: id 2, 3, … The same person ends up in the table many times. This can change query results in unexpected ways.
11.6.4Reading data
String url = "jdbc:sqlite:sample.db";
String sql = "SELECT * FROM users";
try (Connection conn = DriverManager.getConnection(url);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql)) {
// Read and print the rows one by one.
while (rs.next()) {
System.out.println("ID: " + rs.getInt("id")
+ ", Name: " + rs.getString("name")
+ ", Email: " + rs.getString("email"));
}
} catch (SQLException e) {
System.out.println(e.getMessage());
}ID: 1, Name: Ahmet Yılmaz, Email: ahmet@example.comReading is done with executeQuery, which returns a ResultSet. This time the result set is also a resource, so it joins the try-with-resources parentheses as the third resource. rs.next() moves the cursor to the next row; it returns true if there is a row and false if not. getInt("id") and getString("name") read the columns of the current row by name. Since the table has a single row, the loop runs once.
Reading by column name is safer than reading by position. SELECT * returns the columns in the order of the table definition; if a new column is added to the table later, the numbers may shift, while the names do not change. In the SQLite driver, column names are case-insensitive: getString("NAME") works too. A column name that does not exist throws a SQLException: trying getString("title") gave the message no such column: 'title'.
11.6.5Code trace: reading with ResultSet
The while (rs.next()) loop is the most common JDBC pattern. The following program reads a table of two rows. reading.db was prepared before the program with two rows: (1, Ahmet Yılmaz) and (2, Ayşe Demir).
String url = "jdbc:sqlite:reading.db";
String sql = "SELECT * FROM users";
try (Connection conn = DriverManager.getConnection(url);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql)) {
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
System.out.println(id + " - " + name);
}
System.out.println("Done reading.");
} catch (SQLException e) {
System.out.println(e.getMessage());
}1 - Ahmet Yılmaz
2 - Ayşe Demir
Done reading.next() call, sits past the last row (right).| Step | Line | Variables | New output |
|---|---|---|---|
| 1 | 3: try (Connection conn = DriverManager.getConnection(url);4: Statement stmt = conn.createStatement();5: ResultSet rs = stmt.executeQuery(sql)) { | — | — |
| 2 | 6: while (rs.next()) { | rs.next()=true | — |
| 3 | 7: int id = rs.getInt("id");8: String name = rs.getString("name"); | rs.next()=true, id=1, name="Ahmet Yılmaz" | — |
| 4 | 9: System.out.println(id + " - " + name); | rs.next()=true, id=1, name="Ahmet Yılmaz" | 1 - Ahmet Yılmaz |
| 5 | 6: while (rs.next()) { | rs.next()=true, id=1, name="Ahmet Yılmaz" | — |
| 6 | 7: int id = rs.getInt("id");8: String name = rs.getString("name"); | rs.next()=true, id=2, name="Ayşe Demir" | — |
| 7 | 9: System.out.println(id + " - " + name); | rs.next()=true, id=2, name="Ayşe Demir" | 2 - Ayşe Demir |
| 8 | 6: while (rs.next()) { | rs.next()=false | — |
| 9 | 11: System.out.println("Done reading."); | rs.next()=false | Done reading. |
| 10 | 12: } catch (SQLException e) { | — | — |
Table 11.15 gives ten steps. In the first step the connection is opened and the query runs; rs holds the two-row result, and the cursor is before the first row (Figure 11.20, left). In the second step next() moves the cursor to the first row and returns true. In the third and fourth steps the columns are read from the current row and printed. In the fifth step the cursor moves to the second row; the sixth and seventh steps do the same work for the second row. In the eighth step there are no more rows; next() returns false and the loop ends. In the ninth step "Done reading." is printed. In the tenth step the try block ends and rs, stmt, and conn are closed in that order.
next() was called three times in total: once for each of the two rows and once to find out that the rows had ended. In general, for a result of n rows the loop runs n times and next() is called n + 1 times. For an empty result, the first next() returns false and the loop body never runs. This is not an error: a query that matches nothing, such as WHERE id = 99, returns an empty result set.
Reading a column without calling next() first. The cursor is before the first row; there is no row to read. Standard JDBC expects a SQLException in this case. The SQLite driver 3.40.0.0, however, returned the first row's value without an error in the test. This is one driver's own behavior, and on other drivers the code fails. For a single-row result, too, the pattern is if (rs.next()) { … }.
11.6.6Updating and deleting data
Updating and deleting use the same pattern as inserting; only the SQL text changes.
String url = "jdbc:sqlite:sample.db";
String sql = "UPDATE users SET name = 'Mehmet Akdeniz' WHERE id = 1";
try (Connection conn = DriverManager.getConnection(url);
Statement stmt = conn.createStatement()) {
// Update the data in the database.
int n = stmt.executeUpdate(sql);
System.out.println("Data updated! (" + n + " row)");
} catch (SQLException e) {
System.out.println(e.getMessage());
}Data updated! (1 row)Before the update, the read program printed ID: 1, Name: Ahmet Yılmaz, …. After the update, the same program prints this:
ID: 1, Name: Mehmet Akdeniz, Email: ahmet@example.comSET changes only the column named; email stays the same. WHERE id = 1 selects the row to update. executeUpdate returns 1 because a single row satisfied the condition. The delete program has the same structure:
String url = "jdbc:sqlite:sample.db";
String sql = "DELETE FROM users WHERE id = 1";
try (Connection conn = DriverManager.getConnection(url);
Statement stmt = conn.createStatement()) {
// Delete the data from the database.
int n = stmt.executeUpdate(sql);
System.out.println("Data deleted! (" + n + " row)");
} catch (SQLException e) {
System.out.println(e.getMessage());
}When the program is run twice, the output is as follows:
Data deleted! (1 row)Data deleted! (0 row)On the first run, the row with number 1 is deleted. On the second run, no row is left to delete. This is not an error: DELETE deletes the zero rows that satisfy the condition, and executeUpdate returns 0. The program still prints "Data deleted!", which misleads the user. The message should therefore depend on the returned count. A DELETE FROM users without WHERE deletes all rows in the table. The table itself, its structure, remains; the statement that removes a table entirely is DROP TABLE.
11.6.7The three execute methods
Statement has three methods that run SQL. Table 11.16 shows when to use which.
| Method | Returns | Use for |
|---|---|---|
execute | boolean: is there a result set | CREATE TABLE, DROP; SQL of unknown kind |
executeUpdate | int: the number of rows affected | INSERT, UPDATE, DELETE |
executeQuery | ResultSet | SELECT |
What happens if the wrong method is chosen? The following experiment calls each method with a "wrong" statement:
query does not return ResultSet
row count: 1
executeUpdate(SELECT) = 0
execute(INSERT) = false, getUpdateCount = 1
execute(SELECT) = true
execute(CREATE) = false, getUpdateCount = 1
executeUpdate(CREATE) = 0
executeUpdate(DROP) = 0Running INSERT with executeQuery throws a SQLException with the message query does not return ResultSet. The second line is surprising: despite the error, the row was inserted into the table. The SQLite driver ran the statement first and noticed only afterward that there was no result set. It would be wrong for a program to assume "an error occurred, so nothing was inserted". executeUpdate with SELECT raised no error with this driver and returned 0; the standard expects a SQLException. execute accepts every statement and lets you obtain the result afterward with getUpdateCount() or getResultSet(). For CREATE and DROP, executeUpdate returns 0. In short, choose the right method; drivers react to misuse in different ways.
When the six programs are run in sequence from the command line, the screen looks like this:
> java Connect
Connected!
> java CreateTable
Table created!
> java InsertData
Data inserted! (1 row)
> java ReadData
ID: 1, Name: Ahmet Yılmaz, Email: ahmet@example.com
> java UpdateData
Data updated! (1 row)
> java ReadData
ID: 1, Name: Mehmet Akdeniz, Email: ahmet@example.com
> java DeleteData
Data deleted! (1 row)
> java ReadData
> java DeleteData
Data deleted! (0 row)This transcript is identical to the real run. After the delete, ReadData prints nothing: the table exists but is empty, and the loop body never runs. The last DeleteData deletes 0 rows.
11.6.8Code trace: return values of executeUpdate
The number that executeUpdate returns carries the information the program needs to give the right message. The following code inserts three records into a table of supplies, then performs an update and a delete. The insert uses a PreparedStatement. All you need to know here is that the ? marks stand in for values and are filled with setString and setInt.
String[] names = {"stapler", "scissors", "tape"};
int[] stock = {40, 0, 15};
PreparedStatement ins = conn.prepareStatement(
"INSERT INTO supplies(name, stock) VALUES(?, ?)");
for (int i = 0; i < names.length; i++) {
ins.setString(1, names[i]);
ins.setInt(2, stock[i]);
ins.executeUpdate();
}
int updated = stmt.executeUpdate(
"UPDATE supplies SET stock = stock + 10 WHERE stock < 20");
int deleted = stmt.executeUpdate("DELETE FROM supplies WHERE stock > 100");
System.out.println(updated + " updated, " + deleted + " deleted");When the program was run with a connection and a supplies(id, name, stock) table, the value that executeUpdate returned in each round of the insert loop was printed as well. The program's last line and the final state of the table are in the output too:
round 0: 1
round 1: 1
round 2: 1
2 updated, 0 deleted
1 stapler 40
2 scissors 10
3 tape 25| Step | Line | Variables | New output |
|---|---|---|---|
| 1 | 1: String[] names = {"stapler", "scissors", "tape"};2: int[] stock = {40, 0, 15};3: PreparedStatement ins = conn.prepareStatement(4: "INSERT INTO supplies(name, stock) VALUES(?, ?)"); | names=[stapler, scissors, tape], stock=[40, 0, 15] | — |
| 2 | 6: ins.setString(1, names[i]);7: ins.setInt(2, stock[i]); | i=0 | — |
| 3 | 8: ins.executeUpdate(); | i=0, returned=1 | — |
| 4 | 5: for (int i = 0; i < names.length; i++) {6: ins.setString(1, names[i]);7: ins.setInt(2, stock[i]);8: ins.executeUpdate(); | i=1, returned=1 | — |
| 5 | 5: for (int i = 0; i < names.length; i++) {6: ins.setString(1, names[i]);7: ins.setInt(2, stock[i]);8: ins.executeUpdate(); | i=2, returned=1 | — |
| 6 | 10: int updated = stmt.executeUpdate(11: "UPDATE supplies SET stock = stock + 10 WHERE stock < 20"); | updated=2 | — |
| 7 | 12: int deleted = stmt.executeUpdate("DELETE FROM supplies WHERE stock > 100"); | updated=2, deleted=0 | — |
| 8 | 13: System.out.println(updated + " updated, " + deleted + " deleted"); | updated=2, deleted=0 | 2 updated, 0 deleted |
WHERE stock < 20 selects the scissors (0) and tape (15) rows; 10 is added to both.The insert statement is prepared once before the loop; in each round only the values change. Each insert returns 1, and SQLite gives the rows the numbers 1, 2, and 3 in order. In the update, the condition WHERE stock < 20 is satisfied by scissors (0) and tape (15) (Figure 11.21). Ten is added to the stock of both: scissors becomes 10 and tape becomes 25. updated is 2. SET stock = stock + 10 computes the new value from the column's old value; it is the counterpart of stock += 10 in Java.
In the delete, no product has a stock above 100. No error occurs; 0 is simply returned. By looking at these counts, the program can give correct messages such as "no record found". A note on cost: if the WHERE condition is on a column with no index (such as stock), update and delete scan the whole table; in a table of n rows the cost is proportional to n. With a primary key condition such as WHERE id = 1, the row is found directly.
11.7PreparedStatement
The SQL texts so far were fixed. In real programs, the values come from the user: the name to search for, the grade to insert, the number of the record to delete. There is a wrong way and a right way to put these values into the SQL text.
11.7.1SQL injection
The easiest-looking way is to paste the value the user typed into the SQL text by string concatenation. On a search screen the user types the name to look for, and the program builds this text: "SELECT name FROM people WHERE name = '" + input + "'". As long as the input is Ali, all is well. But if the input contains a quotation mark, the structure of the SQL text changes.
SQL injection is an attack in which user input gets mixed into an SQL statement and changes its meaning. The input is interpreted not as a value but as part of the SQL.
String input = "x' OR '1'='1"; // the "name" the user typed
// DANGEROUS: the input is pasted into the SQL text
String sql = "SELECT name FROM people WHERE name = '"
+ input + "'";
System.out.println(sql);
ResultSet rs1 = stmt.executeQuery(sql);
// SAFE: the input is sent only as a value
PreparedStatement ps = conn.prepareStatement(
"SELECT name FROM people WHERE name = ?");
ps.setString(1, input);
ResultSet rs2 = ps.executeQuery();The first half of the code is the dangerous way and the second half is the safe way. With three people named Ali, Ayşe, and Can in the people table, the rows of the two result sets were counted:
SELECT name FROM people WHERE name = 'x' OR '1'='1'
Concatenation: 3 rows
PreparedStatement: 0 rows
input length: 12
[SQLITE_ERROR] SQL error or missing database (near "s": syntax error)
with PreparedStatement: 1
Ali's
INSERT INTO people(name) VALUES('Ali''s')
table still exists: 4The first line of the output is the SQL text that went to the database. The user typed x' OR '1'='1 in place of a name. In the concatenation, the first quotation mark in the input closes the quotation mark the program opened. The name value ends as 'x'. The OR '1'='1' that follows is no longer a value but part of the SQL. The quotation mark the program appended at the very end closes '1, and the text becomes syntactically perfect. The condition is name = 'x' OR '1'='1'; because '1'='1' is true in every row, the condition eliminates no row. Three rows come back.
On a login screen this means signing in without a password. Worse is possible too: the input could be a piece of SQL that deletes data or reads passwords from other tables. SQL injection has for years been among the most common security holes in web applications.
In the second half, the PreparedStatement returns 0 rows with the same input. Here the SQL text is fixed and the place of the input is marked with ?. The input is sent separately with setString(1, input) and used only as a value. The database looks for "the person whose name is exactly x' OR '1'='1". This 12-character text is nobody's name.
The last lines of the output show two more side results. When a text with an apostrophe, such as Ali's, is inserted by concatenation, the SQL breaks and the message near "s": syntax error is received. Even an ordinary user with no intent to attack can break the program. With PreparedStatement the same text is inserted and read back without trouble. Doubling the quote by hand ('') is another way, but it is error-prone; a single forgotten spot leaves the whole program vulnerable. The SQLite driver's executeQuery did not run a second statement appended with a semicolon (after the DROP TABLE attempt the table was still there). This does not count as protection: an attack that stays inside a single statement, like the one above, still works.
11.7.2Code trace: SQL injection
The following code compares the two ways by row count:
String input = "x' OR '1'='1";
String sql = "SELECT name FROM people WHERE name = '"
+ input + "'";
int n = 0;
try (ResultSet rs = stmt.executeQuery(sql)) {
while (rs.next()) n++;
}
System.out.println("Concatenation: " + n + " rows");
PreparedStatement ps = conn.prepareStatement(
"SELECT name FROM people WHERE name = ?");
ps.setString(1, input);
n = 0;
try (ResultSet rs = ps.executeQuery()) { while (rs.next()) n++; }
System.out.println("PreparedStatement: " + n + " rows");PreparedStatement the input is a single text value and matches no name (right).| Step | Line | Variables | New output |
|---|---|---|---|
| 1 | 1: String input = "x' OR '1'='1"; | input=x' OR '1'='1 | — |
| 2 | 2: String sql = "SELECT name FROM people WHERE name = '"3: + input + "'"; | sql=SELECT … WHERE name = 'x' OR '1'='1' | — |
| 3 | 5: try (ResultSet rs = stmt.executeQuery(sql)) { | rs=ResultSet | — |
| 4 | 5: try (ResultSet rs = stmt.executeQuery(sql)) { | rs=ResultSet | — |
| 5 | 6: while (rs.next()) n++;7: } | n=3 | — |
| 6 | 8: System.out.println("Concatenation: " + n + " rows"); | n=3 | Concatenation: 3 rows |
| 7 | 9: PreparedStatement ps = conn.prepareStatement(10: "SELECT name FROM people WHERE name = ?"); | ps=PreparedStatement | — |
| 8 | 11: ps.setString(1, input); | 1. ?=x' OR '1'='1 | — |
| 9 | 13: try (ResultSet rs = ps.executeQuery()) { while (rs.next()) n++; } | n=0 | — |
| 10 | 14: System.out.println("PreparedStatement: " + n + " rows"); | n=0 | PreparedStatement: 0 rows |
In the third and fourth steps, the database evaluates the condition for each row. For Ali, 'Ali'='x' is false, but the right side of the OR is always true; the row is selected. Ayşe and Can are selected for the same reason (Figure 11.22, left). In the seventh step the SQL is compiled first; ? is only the place of a value. The structure of the statement is settled at this point and cannot change, whatever the input. In the eighth step the input is bound as a single text value as a whole; the quotation marks in it are ordinary characters. In the ninth step no name equals this text. The same input gives two different results. The rule is firm: a value that comes from the user is always given to SQL with ?.
11.7.3Placeholders
A prepared statement (PreparedStatement) is an SQL statement that contains ? placeholders in place of values and takes the values separately. It is created with the connection's prepareStatement(sql) method; the placeholders are filled with setXxx(index, value) methods.
The following method inserts a person into the people table:
static void add(Connection conn, String name, String surname,
int age) throws SQLException {
String sql = "INSERT INTO people(name, surname, age) "
+ "VALUES(?, ?, ?)";
try (PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setString(1, name); // 1st question mark
ps.setString(2, surname); // 2nd question mark
ps.setInt(3, age); // 3rd question mark
ps.executeUpdate();
}
}There are three ? in the SQL text. The first argument of the setXxx methods is the index of the placeholder; the index starts at 1 and follows the left-to-right order in the SQL text (Figure 11.23). The method name says the Java type of the value: setString for text, setInt for an integer, setDouble for a floating-point number. After all placeholders are filled, executeUpdate() is called without parameters, because the SQL text was given when the statement was prepared.
setString and setInt calls fill the question marks in order, with numbers starting at 1.PreparedStatement has three benefits. The first is security: it prevents SQL injection. The second is that there is no quoting problem: "Ali's" is saved without trouble. The third is reuse: the same statement is prepared once and run again and again with different values. The DBMS does not parse the statement anew each time; the difference is noticeable when thousands of inserts are made in a loop.
Placeholders can stand in only for values. A table or column name cannot be given with ?: preparing SELECT * FROM ? gave the message near "?": syntax error. A '?' inside quotes is not a placeholder but a question-mark character; in the query WHERE name = '?', a setString(1, …) call fails. A placeholder that is not filled counts as NULL. When the insert with three placeholders was run with only two values given, the message NOT NULL constraint failed: people.age was received. One more detail: a value that has been set stays in place until a new setXxx call. When, after an insert, only setString(1, "Bora") was changed and the statement was run again, the second row took the previous row's surname and age.
Starting the placeholder index at 0: ps.setInt(0, 5). The standard expects a SQLException in this case. The SQLite driver 3.40.0.0, however, threw an unchecked ArrayIndexOutOfBoundsException (Index -1 out of bounds for length 3). This exception is not caught by catch (SQLException e) and stops the program. The index always starts at 1 and does not exceed the number of ?.
11.7.4The people program
The insert method, together with methods for updating, deleting, and listing, makes up a small but complete program. The update and delete methods are as follows:
static void update(Connection conn, String name, String surname,
int age) throws SQLException {
String sql = "UPDATE people SET surname = ?, age = ? "
+ "WHERE name = ?";
try (PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setString(1, surname);
ps.setInt(2, age);
ps.setString(3, name);
ps.executeUpdate();
}
}
static void delete(Connection conn, String name) throws SQLException {
String sql = "DELETE FROM people WHERE name = ?";
try (PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setString(1, name);
ps.executeUpdate();
}
}Each method takes the Connection as a parameter. The connection is opened once in main and used for many jobs. Opening a new connection for every operation is both slow and unnecessary. A PreparedStatement, on the other hand, is opened in each method's own try-with-resources block and closed when the method ends; the connection stays open.
In the update method, pay attention to the order of the ? marks. The SQL text is SET surname = ?, age = ? WHERE name = ?. Although the method's parameter order is (name, surname, age), in the SQL the name is the third placeholder. That is why setString(3, name) is written. The numbers follow the SQL text, not the Java parameters.
The methods pass errors to the caller with throws SQLException. Because main also declares throws SQLException, if an error occurs the program stops with a stack trace. For a small example program this is acceptable. In a real program the error is caught in main and the user is given an understandable message. The listing method is as follows:
static void list(Connection conn) throws SQLException {
String sql = "SELECT id, name, surname, age FROM people";
try (Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(sql)) {
while (rs.next()) {
System.out.println(rs.getInt("id") + " " + rs.getString("name")
+ " " + rs.getString("surname") + " " + rs.getInt("age"));
}
System.out.println("---");
}
}This query has no variable value; a plain Statement is enough. Since there is no user input, there is no injection risk either. Each call to list reads the table as it is at that moment and prints --- at the end. Finally, main calls the methods in order:
public static void main(String[] args) throws SQLException {
String url = "jdbc:sqlite:people.db";
try (Connection conn = DriverManager.getConnection(url);
Statement stmt = conn.createStatement()) {
stmt.execute("CREATE TABLE IF NOT EXISTS people ("
+ "id INTEGER PRIMARY KEY, name TEXT NOT NULL, "
+ "surname TEXT NOT NULL, age INTEGER NOT NULL)");
add(conn, "Ahmet", "Yılmaz", 30);
add(conn, "Ayşe", "Demir", 40);
update(conn, "Ahmet", "Akdeniz", 35);
list(conn);
delete(conn, "Ahmet");
list(conn);
}
}The four methods and main were combined in a single Person class and run in an empty folder:
1 Ahmet Akdeniz 35
2 Ayşe Demir 40
---
2 Ayşe Demir 40
---11.7.5Code trace: the people program
| Step | Line | Variables | New output |
|---|---|---|---|
| 1 | 3: try (Connection conn = DriverManager.getConnection(url);4: Statement stmt = conn.createStatement()) { | — | — |
| 2 | 5: stmt.execute("CREATE TABLE IF NOT EXISTS people ("6: + "id INTEGER PRIMARY KEY, name TEXT NOT NULL, "7: + "surname TEXT NOT NULL, age INTEGER NOT NULL)"); | — | — |
| 3 | 8: add(conn, "Ahmet", "Yılmaz", 30); | — | — |
| 4 | 9: add(conn, "Ayşe", "Demir", 40); | — | — |
| 5 | 10: update(conn, "Ahmet", "Akdeniz", 35); | — | — |
| 6 | 11: list(conn); | — | 1 Ahmet Akdeniz 35 ⏎ 2 Ayşe Demir 40 ⏎ --- |
| 7 | 12: delete(conn, "Ahmet"); | — | — |
| 8 | 13: list(conn); | — | 2 Ayşe Demir 40 ⏎ --- |
| 9 | 14: } | — | — |
people table after the update (left) and after the delete (right).In the first step, people.db is created if it does not exist; the connection and stmt are opened. In the second step the table is created and is still empty. In the third and fourth steps add is called; Ahmet is inserted with id = 1 and Ayşe with id = 2. In the fifth step WHERE name = ? selects Ahmet; his surname becomes Akdeniz and his age 35. In the sixth step list prints the two rows and ---. In the seventh step Ahmet's row is deleted. In the eighth step only Ayşe is left in the table. In the ninth step the connection is closed; the data persists in people.db (Figure 11.24).
A note on cost can be added. update and delete work with WHERE name = ?. Because there is no index on the name column, each call scans the table. Moreover, if two people have the same name, both are updated or deleted. Working with the primary key (WHERE id = ?) is both fast and exact.
11.8Advanced JDBC
11.8.1Generated keys: getGeneratedKeys
The database decides the id of a new row. A program often wants to know this number right away. When an order is inserted, its line items go into a separate table together with the order's id. The way to learn the number is getGeneratedKeys():
String sql = "INSERT INTO students(name, dept_id) "
+ "VALUES(?, ?)";
try (PreparedStatement ps = conn.prepareStatement(sql,
Statement.RETURN_GENERATED_KEYS)) {
ps.setString(1, "Ece");
ps.setInt(2, 3);
ps.executeUpdate();
try (ResultSet k = ps.getGeneratedKeys()) {
if (k.next()) {
System.out.println("New id: " + k.getInt(1));
}
}
}New id: 5
id INTEGER PRIMARY KEY -> 3
id INTEGER PRIMARY KEY AUTOINCREMENT -> 4
after deleting from the middle: 1,3,4
last_insert_rowid: 5Statement.RETURN_GENERATED_KEYS is passed to prepareStatement as the second argument. This constant tells the driver to keep the generated keys. After executeUpdate, getGeneratedKeys() returns a ResultSet. The single row and single column of this result set hold the new key. The table already had four students (Ada, Bora, Cem, Deniz); Ece got number 5. Because the new key is also a result set, it is opened and closed with try-with-resources.
The next two lines of the output show a subtlety of numbering. Rows 1, 2, and 3 are inserted into a table, 3 is deleted, and a new row is inserted. Which number does the new row get? Table 11.20 compares the two definitions.
| Column definition | New id |
|---|---|
id INTEGER PRIMARY KEY | 3 (largest id + 1) |
id INTEGER PRIMARY KEY AUTOINCREMENT | 4 (a used number is never given again) |
Plain INTEGER PRIMARY KEY gives one more than the largest existing number. If the largest number is deleted, that number is reused. If a number in the middle is deleted (for example 2), the new row still gets 4; the gap is not filled. AUTOINCREMENT stores the largest number used so far in a separate table and never hands out a number again. If the number of a deleted record must not pass to another record (an invoice number, an order number), AUTOINCREMENT is used. Its counterpart in MySQL is AUTO_INCREMENT.
11.8.2From rows to objects: the DAO pattern
The programs so far scattered SQL and row reading throughout main. In an object-oriented program, each row is instead converted to an object, and the SQL is collected in one place. A simple class is enough for student rows:
class Student {
private final int id;
private final String name;
Student(int id, String name) {
this.id = id;
this.name = name;
}
public String toString() {
return "#" + id + " " + name;
}
}The fields of the Student class are final; the object does not change after it is created. toString writes the object in the form #1 Ada. This class knows nothing about the database: it contains neither SQL nor JDBC.
A data access object (DAO) is a design that collects all of a table's SQL operations in a single class and returns the results as objects. The rest of the program sees no SQL; it only calls the DAO's methods.
Table 11.21 lists the methods of a StudentDao class. Each method corresponds to one SQL statement and returns the result in Java's terms: an object instead of a row, a list instead of a result set, a boolean instead of the number of rows affected.
StudentDao method | SQL | Returns |
|---|---|---|
add(name, dept) | INSERT | the new id |
find(id) | SELECT … WHERE id = ? | Student or null |
inDept(dept) | SELECT … WHERE dept_id = ? | List<Student> |
delete(id) | DELETE | whether a row was deleted (boolean) |
StudentDao, JDBC, and the database file. Requests go down, objects go up.Figure 11.25 shows the layered structure. The user interface (main or a Swing window) knows only StudentDao and asks it for a List<Student>. The DAO works with JDBC and SQL. The SQL is only in this class. If the database changes or the tables are reorganized, only the DAO changes; the interface code stays the same. This is the database-level counterpart of encapsulation. The connection is given to the DAO through its constructor; the DAO neither opens nor closes the connection.
All four methods in the table were written and run. On a table holding Ada, Bora, Cem, and Deniz, the results are as follows:
add -> 5
find(2) -> #2 Bora
find(9) -> null
inDept(1) -> [#1 Ada, #3 Cem, #5 Ece]
delete(3) -> true
delete(3) -> false
inDept(1) -> [#1 Ada, #5 Ece]add returns Ece's number (5) through getGeneratedKeys. find(9) finds no row and returns null; the calling code must check for it. delete(3) returns true on the first call and false on the second, because executeUpdate gives 0 the second time. The DAO converts this count to a boolean, shielding the rest of the program from the details of SQL.
In this example, mapping rows to objects was done by hand. In large projects, ORM (object-relational mapping) libraries do this automatically, for example the JPA standard and Hibernate, one of its implementations. Annotations declare which columns the class fields correspond to, and the library generates most of the SQL itself. JDBC still runs behind an ORM; what you learn in this chapter is also the foundation for understanding those libraries.
11.8.3Code trace: from row to object
The following method returns the students in a department as a list of objects; the last two lines call it from main:
static List<Student> inDept(Connection conn,
int dept) throws SQLException {
List<Student> list = new ArrayList<>();
String sql = "SELECT id, name FROM students "
+ "WHERE dept_id = ? ORDER BY id";
try (PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setInt(1, dept);
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
list.add(new Student(rs.getInt("id"),
rs.getString("name")));
}
}
}
return list;
}
// inside main:
List<Student> list = inDept(conn, 1);
for (Student s : list) System.out.println(s);#1 Ada
#3 Cem
dept 3: []
dept 2: [#2 Bora]| Step | Line | Call stack | Variables | New output |
|---|---|---|---|---|
| 1 | 18: List<Student> list = inDept(conn, 1); | main() → inDept(conn, 1) | dept=1 | — |
| 2 | 3: List<Student> list = new ArrayList<>();4: String sql = "SELECT id, name FROM students "5: + "WHERE dept_id = ? ORDER BY id";6: try (PreparedStatement ps = conn.prepareStatement(sql)) { | main() → inDept(conn, 1) | dept=1, list=[] | — |
| 3 | 7: ps.setInt(1, dept);8: try (ResultSet rs = ps.executeQuery()) { | main() → inDept(conn, 1) | dept=1, list=[] | — |
| 4 | 9: while (rs.next()) {10: list.add(new Student(rs.getInt("id"),11: rs.getString("name"))); | main() → inDept(conn, 1) | list=[#1 Ada] | — |
| 5 | 9: while (rs.next()) {10: list.add(new Student(rs.getInt("id"),11: rs.getString("name"))); | main() → inDept(conn, 1) | list=[#1 Ada, #3 Cem] | — |
| 6 | 9: while (rs.next()) {13: }14: } | main() → inDept(conn, 1) | list=[#1 Ada, #3 Cem] | — |
| 7 | 15: return list;18: List<Student> list = inDept(conn, 1); | main() | list=[#1 Ada, #3 Cem] | — |
| 8 | 19: for (Student s : list) System.out.println(s); | main() | list=[#1 Ada, #3 Cem] | #1 Ada ⏎ #3 Cem |
Student objects.main calls the method with dept = 1; the connection is open in main. The method creates an empty list and prepares the query with ?. ? = 1 is bound and the query runs; department 1 has Ada and Cem. From the first row, id = 1 and name = Ada are read and new Student(1, "Ada") is added to the list. The second row produces the second object: #3 Cem (Figure 11.26). When next() returns false, the two nested try blocks end; first rs and then ps is closed. The connection is closed by main, which opened it. The method returns the two-element list, and its frame is removed from the stack. main prints each object with toString(); it knows nothing about SQL.
The last two lines of the output are the results of the same method for other departments. Department 3 (ME) has no students; the method returns an empty list, not null, and [] is printed. Returning an empty list is safer than null: if the calling code walks the list with a for loop, the loop simply does not run, and there is no risk of NullPointerException. The cost of the method is the cost of the query plus that of creating k objects, where k is the number of students in the department. The list takes memory for k objects. For very large results, it may be necessary to process rows one at a time instead of filling them all into a list.
11.8.4The same code, another database: MySQL
The promise of JDBC is that the same code also works with other databases. The following program reads the users table on a MySQL server:
String url = "jdbc:mysql://localhost:3306/testdb";
String user = "root";
String password = "secret";
String sql = "SELECT id, name, email FROM users";
try (Connection conn =
DriverManager.getConnection(url, user, password);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql)) {
while (rs.next()) {
System.out.println(rs.getInt("id") + " "
+ rs.getString("name"));
}
} catch (SQLException e) {
System.out.println(e.getMessage());
}The JDBC code is the same as in the SQLite example. Four things change: the connection URL, the user name, the password, and the driver jar on the classpath. MySQL's driver is mysql-connector-j. The URL has the form jdbc:mysql://localhost:3306/testdb: localhost is the machine the server runs on, 3306 is MySQL's default port, and testdb is the name of the database. The three-argument form of getConnection also takes the user name and password.
MySQL is a server. Before the program runs, the server must be installed and running, and the testdb database and the users table must have been created. There is no "create the file if it does not exist" behavior as in SQLite. The machine on which this chapter was prepared had no MySQL driver. When the program was compiled and run, it gave the message No suitable driver found for jdbc:mysql://localhost:3306/testdb; this message is the expected behavior.
The name of the driver class is com.mysql.cj.jdbc.Driver. The name com.mysql.jdbc.Driver seen in old code is deprecated. Since the driver has been loaded automatically since JDBC 4.0, this name is not written in the code anyway. One last warning: in real projects, the password is not written in the code. A password written in code is plainly visible in the compiled .class file and in the version control system. The password is read from a configuration file or an environment variable, for example with System.getenv("DB_PASSWORD").
11.9Transactions
So far, each SQL statement has run on its own and become permanent immediately. Some jobs, however, consist of several statements that make sense only together. This section explains how to run such jobs safely.
11.9.1Transactions and ACID
Consider a money transfer: Ali sends 300 TL to Ece. The job is two UPDATE statements: 300 TL is added to Ece's account, and 300 TL is subtracted from Ali's. What happens if the power fails after the first statement has run, or if the second statement does not run because of an error? Ece's money has increased and Ali's has not decreased: money has appeared out of nothing. Had the order of the statements been reversed, money would have vanished. It is unacceptable for one of the two statements to happen and the other not.
A transaction is one or more SQL statements run as a single unit of work. Either all the statements of the transaction become permanent together, or none does. Making them permanent is called commit, and undoing them is called rollback.
In JDBC, the default setting of a connection is auto-commit: each statement is a transaction on its own and becomes permanent as soon as it runs. This setting was queried on a SQLite connection with conn.getAutoCommit() and came out true. The pattern for grouping several statements into one transaction is fixed. conn.setAutoCommit(false) starts a transaction, and then the statements run. If all goes well, conn.commit() makes the changes permanent; if an error occurs, conn.rollback() undoes them (Figure 11.27).
setAutoCommit(false) are temporary; commit() makes them permanent and rollback() undoes them.A reliable transaction has four properties, known by their initials as ACID.
- Atomicity: either the whole transaction is applied or none of it. Only one of the transfer's two statements cannot become permanent.
- Consistency: all constraints hold at the end of the transaction. If there is a
CHECK (balance >= 0), no transaction can end by pushing a balance below zero. - Isolation: concurrent transactions do not see each other's half-done work. If another program reads Ece's balance while the transfer is under way, it sees either the value before the transfer or the value after it, never the one in between.
- Durability: committed data is not lost even if the power fails right afterward. The DBMS completes the commit only after the change has been safely written to disk.
Isolation can be seen in an experiment. Two separate connections were opened to the same bank.db file. The first connection turned off auto-commit and raised Ece's balance from 500 to 800, without committing yet. Meanwhile, both connections read the same row:
a sees: 800
b sees: 500
after commit b sees: 800The connection that made the change sees its own temporary value (800). The second connection does not see the uncommitted change and reads 500. After the commit, the second connection also sees 800.
11.9.2A money transfer
The transfer program has two parts. main sets up an in-memory database, inserts two accounts, and tries two transfers:
static final String DEPOSIT =
"UPDATE accounts SET balance = balance + ? WHERE id = ?";
static final String WITHDRAW =
"UPDATE accounts SET balance = balance - ? WHERE id = ?";
public static void main(String[] args) throws SQLException {
String url = "jdbc:sqlite::memory:"; // in memory, temporary
try (Connection conn = DriverManager.getConnection(url);
Statement st = conn.createStatement()) {
st.execute("CREATE TABLE accounts (id INTEGER PRIMARY KEY, "
+ "owner TEXT, balance INTEGER CHECK (balance >= 0))");
st.execute("INSERT INTO accounts(owner, balance) "
+ "VALUES ('Ali', 1000), ('Ece', 500)");
transfer(conn, 1, 2, 300); // Ali → Ece 300 TL
transfer(conn, 1, 2, 5000); // Ali can't afford it
printAll(conn);
}
}The balance column of the accounts table has the constraint CHECK (balance >= 0). Any statement that pushes a balance below zero throws a SQLException. In the second transfer, Ali's 700 TL is not enough for a 5000 TL transfer. The transfer method is as follows:
static void transfer(Connection conn, int from, int to,
int amount) throws SQLException {
conn.setAutoCommit(false); // transaction starts
try (PreparedStatement p1 = conn.prepareStatement(DEPOSIT);
PreparedStatement p2 = conn.prepareStatement(WITHDRAW)) {
p1.setInt(1, amount); p1.setInt(2, to);
p1.executeUpdate(); // deposit to receiver
p2.setInt(1, amount); p2.setInt(2, from);
p2.executeUpdate(); // withdraw from sender
conn.commit(); // make permanent
System.out.println(amount + " TL transferred.");
} catch (SQLException e) {
conn.rollback(); // undo
System.out.println("Rolled back: " + amount + " TL");
} finally {
conn.setAutoCommit(true);
}
}The method first turns off auto-commit; the transaction begins. With two PreparedStatements it first deposits to the receiver and then withdraws from the sender. If both statements succeed, commit() makes both permanent together. If either statement throws a SQLException, control passes to catch, and rollback() undoes all the changes in the transaction. The finally block turns auto-commit back on no matter which path was taken; the connection returns to its default state for later users. The printAll method is a SELECT loop like list and prints each account's owner and balance. When run, the program gives this output:
300 TL transferred.
Rolled back: 5000 TL
Ali: 700
Ece: 80011.9.3Code trace: commit and rollback
Table 11.23 gives the balances and the state of the transaction through the two transfers. The "temporary" entries mark changes that have not been committed.
| Step | Line | Event | Ali | Ece | State | New output |
|---|---|---|---|---|---|---|
| 1 | 3 | setAutoCommit(false): first transfer, the transaction begins | 1000 | 500 | permanent | — |
| 2 | 6–7 | 300 is deposited to Ece | 1000 | 800 | temporary | — |
| 3 | 8–9 | 300 is withdrawn from Ali; the constraint holds | 700 | 800 | temporary | — |
| 4 | 10–11 | commit(): both changes become permanent together | 700 | 800 | permanent | 300 TL transferred. |
| 5 | 16 | finally: auto-commit is turned back on | 700 | 800 | permanent | — |
| 6 | 3, 6–7 | Second transfer: 5000 is deposited to Ece | 700 | 5800 | temporary | — |
| 7 | 8–9 | 700 − 5000 < 0: CHECK is violated, SQLException | 700 | 5800 | temporary | — |
| 8 | 12–14 | rollback(): the temporary deposit is undone | 700 | 800 | permanent | Rolled back: 5000 TL |
rollback() (right).The first transfer is trouble-free: the two statements are applied temporarily, and commit() makes both permanent together. In the second transfer, the deposit succeeds and Ece's balance rises temporarily to 5800 (Figure 11.28, left). The withdrawal would make Ali's balance −4300, so it runs into the CHECK constraint and a SQLException is thrown. Ali's balance never changes: the rejected statement is not applied. The commit() line is never reached. The rollback() in the catch block also undoes the deposit made so far in the transaction; Ece's balance returns to 800. Money has neither vanished nor multiplied: there was 1500 TL at the start, and at the end there is 700 + 800 = 1500 TL.
The value of this program becomes clear when you look at what would happen without a transaction. setAutoCommit(false), commit(), and rollback() were removed from the same method and the program was run again:
300 TL transferred.
Rolled back: 5000 TL
([SQLITE_CONSTRAINT_CHECK] A CHECK constraint failed (CHECK constraint failed: balance >= 0))
Ali: 700
Ece: 5800In the second transfer, the deposit became permanent the moment it ran. The withdrawal was rejected, but there was no transaction to roll back. The program still printed "Rolled back", but wrongly: Ece's account holds 5800 TL, and 5000 TL has appeared out of nothing. The total money has risen to 6500 TL.
Forgetting rollback() in the catch block. If a statement fails while auto-commit is off and rollback() is not called, the transaction's successful statements wait in a pending state. Then the setAutoCommit(true) in finally runs. By JDBC rules, turning auto-commit on during a transaction commits it. In the test, the 5000 TL deposited to Ece became permanent this way: Ali 1000, Ece 5500. The error was caught, but the data was corrupted. Always call rollback() on the error path.
11.9.4Batch processing
Writing 1000 values from a measuring device into a table takes 1000 INSERTs. These statements can be sent one by one, or collected in a queue and sent together.
A batch update collects many statements in a queue with addBatch() and sends them together with executeBatch(). executeBatch() returns the number of rows each statement affected, as an int[] array.
conn.setAutoCommit(false);
try (PreparedStatement ps = conn.prepareStatement(
"INSERT INTO readings(value) VALUES(?)")) {
for (int i = 1; i <= 1000; i++) {
ps.setInt(1, i);
ps.addBatch();
}
int[] result = ps.executeBatch();
conn.commit();
System.out.println(result.length + " statements, "
+ "the first affected " + result[0] + " row");
} catch (SQLException e) {
conn.rollback();
throw e;
} finally {
conn.setAutoCommit(true);
}1000 statements, the first affected 1 row
1000 rows, total 500500In each round of the loop the placeholder is filled and addBatch() adds the filled statement to the queue. When the loop ends, the queue holds 1000 statements. executeBatch() sends them all and returns an array of 1000 elements; each element is 1, because each insert affected one row. The second line of the output was added as a check. The table has 1000 rows; the sum of the values is 1 + 2 + … + 1000 = 1000 · 1001 / 2 = 500,500.
The speed of this code comes from two sources: a single transaction and batched sending. With auto-commit on, every INSERT is a separate transaction. At the end of each transaction, SQLite has the data written to disk to guarantee durability and waits for the write to finish. Three measurements were made with a .db file on disk (Table 11.24).
| Method | Run 1 | Run 2 | Run 3 |
|---|---|---|---|
| One at a time, auto-commit on | 1841 | 2047 | 1864 |
addBatch + one transaction | 7 | 8 | 9 |
One executeUpdate at a time + one transaction | 2 | 2 | 2 |
With auto-commit on, 1000 rows took about 2 seconds; with a single transaction, the same job finished in a few milliseconds. The difference is hundreds of times. The last row of the table carries an instructive detail: in SQLite, the main gain comes from the single transaction. Even if the statements are sent one by one, they are as fast as batched sending when they are inside a single transaction. The reason is that SQLite runs inside the program; sending a statement is just a method call. On a server such as MySQL, each statement needs a network round trip, and addBatch also reduces the number of round trips.
Because the whole queue is a single transaction, if one statement fails, rollback() undoes the effect of the whole queue. To see this, the constraint CHECK (value <> 500) was added to the table and the same code was run:
SQLiteException: [SQLITE_CONSTRAINT_CHECK] A CHECK constraint failed (CHECK constraint failed: value <> 500)
0 rows in the tableThe 500th statement was rejected, the catch block called rollback(), and the table stayed empty: all or nothing. After the rollback, the exception is rethrown with throw e;; the error is not silently swallowed, and the caller learns that the operation failed. The finally block turns auto-commit back on, on success and on failure alike. The standard specifies that a failure in a batch is reported with BatchUpdateException, a subclass of SQLException. The SQLite driver threw its own SQLiteException here. Because both are SQLExceptions, catch (SQLException e) catches both cases.
For very large loads, the queue is sent in pieces. For example, executeBatch is called after every 500 addBatch calls. This way a million statements do not pile up in memory, and memory does not balloon; the transaction can still end with a single commit.
11.10Worked examples and exercises
On an empty database the following statements run in order. Which rows does the last SELECT return?
CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT);
INSERT INTO users(name) VALUES ('Ali');
INSERT INTO users(name) VALUES ('Can');
DELETE FROM users WHERE id = 2;
INSERT INTO users(name) VALUES ('Ece');
UPDATE users SET name = 'Efe' WHERE id = 1;
SELECT * FROM users;Ali gets number 1 and Can gets 2. When Can is deleted, the largest id in the table becomes 1. Ece gets the largest id + 1 = 2: the deleted number has been reused. The UPDATE changes only the row with number 1; Ali's name becomes Efe. The result is (1, Efe) and (2, Ece). The statements were verified by running them through JDBC. If the table had been defined with AUTOINCREMENT, Ece would have got 3.
The people program is run a second time with people.db. What are the first block of the output (up to the first ---) and the last block?
The file is persistent. Ayşe (id 2) was left from the first run, and CREATE TABLE IF NOT EXISTS does not drop the table. The new records get numbers 3 (Ahmet) and 4 (Ayşe) by the largest-id-plus-1 rule. update makes Ahmet Akdeniz 35. First block: 2 Ayşe Demir 40, 3 Ahmet Akdeniz 35, 4 Ayşe Demir 40. delete deletes Ahmet. Last block: 2 Ayşe Demir 40, 4 Ayşe Demir 40. The same person is now recorded twice. The second run of the program really gave this output:
2 Ayşe Demir 40
3 Ahmet Akdeniz 35
4 Ayşe Demir 40
---
2 Ayşe Demir 40
4 Ayşe Demir 40
---This result shows a design gap. If the same person should not be added twice, add a constraint such as UNIQUE(name, surname) to the table, or have the program check whether the person exists before inserting.
A login screen is checked with the following code. The table has three people. If the user types ahmet as the name and ' OR '1'='1 as the password, what SQL is produced, how many rows come back, and does the login succeed?
String sql = "SELECT * FROM people WHERE name = '" + name
+ "' AND password = '" + password + "'";
ResultSet rs = stmt.executeQuery(sql);
boolean loggedIn = rs.next();The concatenation produces this text: SELECT * FROM people WHERE name = 'ahmet' AND password = '' OR '1'='1'. In SQL, AND is applied before OR. The condition reads (name = 'ahmet' AND password = '') OR '1'='1'. The right side is true in every row; 3 rows come back. rs.next() returns true and the login succeeds without the password. The fix is to use a PreparedStatement with WHERE name = ? AND password = ?; with the same input, 0 rows come back. All three were verified by running them:
SELECT * FROM people WHERE name = 'ahmet' AND password = '' OR '1'='1'
login: true, rows: 3
PreparedStatement login: false
correct password: true
SELECT * FROM people WHERE name = 'ahmet' --' AND password = 'wrong'
login with comment: trueThe last two lines of the output show another form of attack. If ahmet' -- is typed in the name field, -- starts an SQL comment and the password condition is never read; the login succeeds even with a wrong password. In real systems, passwords are not stored as plain text anyway but as hashes.
If the lines setAutoCommit(false), commit(), and rollback() were removed from the transfer method, what would Ali's and Ece's balances be at the end of the program?
The first transfer succeeds in the same way: Ali 700, Ece 800. In the second transfer, the deposit becomes permanent immediately and Ece rises to 5800. The withdrawal fails because of the CHECK, and there is no transaction to roll back. The result: Ali 700, Ece 5800. 5000 TL has appeared out of nothing, and the program still prints "Rolled back". The program was run in this form to verify this.
The solutions to the four exercises in the slides were also tried with JDK 21 and the SQLite driver. The first exercise fixes the delete program so that it prints a message according to the return value of executeUpdate:
int n = stmt.executeUpdate(sql);
if (n > 0) System.out.println("Data deleted!");
else System.out.println("No record found.");When the program tried to delete the same row twice, it printed "Data deleted!" first and then "No record found." In the second exercise, Ada (60, 70), Bora (30, 50), and Cem (80, 40) are inserted into the students(id, name, midterm, final) table in a loop with a PreparedStatement. Those whose average (midterm 40 percent, final 60 percent) is 50 or above are listed in descending order:
SELECT name, midterm * 0.4 + final * 0.6 AS average FROM students
WHERE midterm * 0.4 + final * 0.6 >= 50 ORDER BY average DESCAda's average is 60 · 0.4 + 70 · 0.6 = 24 + 42 = 66. Bora's is 12 + 30 = 42, and Cem's is 32 + 24 = 56. Bora is dropped; the output is Ada 66.0 and Cem 56.0. The value is read with getDouble("average"). The expression is repeated in WHERE because in the logical order WHERE comes before SELECT, and the alias average is not yet defined. ORDER BY, however, can use the alias. Because the coefficients are written as decimals such as 0.4, the result is REAL. An integer expression such as (midterm * 4 + final * 6) / 10, on the other hand, does integer division in SQLite and drops the fractional part.
The third exercise is a menu-driven program: 1-Add, 2-Update, 3-Delete, 4-List. The menu is built with Scanner and switch. Because nextInt() leaves the end of the line in the buffer, a nextLine() is called after it; otherwise the next name read returns an empty string. Update is done with UPDATE … WHERE id = ? and delete with DELETE … WHERE id = ?. If the number returned by executeUpdate is 0, there is no user with that id, and "User not found." is printed. The fourth exercise saves game scores in a scores(player, score) table with INSERT INTO scores(player, score) VALUES(?, ?). The top 10 scores are listed with SELECT player, score FROM scores ORDER BY score DESC LIMIT ? and ps.setInt(1, 10). The value of LIMIT can also be given with a placeholder; on a table with 12 scores, the query returned 10 rows in descending order.
11.11Common mistakes
The mistakes mentioned throughout the chapter are collected here with their real messages. Table 11.25 lists JDBC and basic SQL mistakes, and Table 11.26 lists mistakes with relationships, grouping, and transactions. The messages are taken from the getMessage() output of SQLite JDBC 3.40.0.0; the driver prefixes each message with an error code such as [SQLITE_ERROR] SQL error or missing database, and the table gives only the actual message in parentheses.
| Mistake | Example and message |
|---|---|
| Driver not on the classpath | Jar not added: No suitable driver found for jdbc:sqlite:sample.db |
Not handling SQLException | No try or throws (compile error): unreported exception SQLException; must be caught or declared to be thrown |
| Table missing or misnamed | Query before the table is created: no such table: users |
| Writing text without quotes | VALUES(Ahmet, …): no such column: Ahmet |
| Concatenating text that contains an apostrophe | VALUES('Ali's'): near "s": syntax error |
The wrong execute method | INSERT with executeQuery: query does not return ResultSet (the row is inserted anyway) |
| Starting column numbers at 0 | rs.getString(0): column 0 out of bounds [1,3] |
UPDATE/DELETE without WHERE | No error; it changes or deletes all rows (returns 3 on a table of three rows) |
| Mistake | Example and result |
|---|---|
Comparing with = NULL | WHERE dept_id = NULL raises no error and returns 0 rows. The right form is IS NULL. |
A join without ON | FROM students, depts: every row matches every row, 4 × 3 = 12 rows. |
| Ambiguous column name | Both tables have name and no table name is given: ambiguous column name: name |
An aggregate function in WHERE | A group condition goes in HAVING: misuse of aggregate: SUM() |
| Not enabling foreign key checking | In SQLite, without PRAGMA foreign_keys = ON, dept_id = 9 is silently accepted. |
Calling wasNull() too late | It looks at the last column read; call it right after the relevant getInt. |
| Selecting an ungrouped column | SELECT customer, amount … GROUP BY customer: SQLite returns the amount of one of the rows in the group; in many databases this is an error. |
Thousands of INSERTs with auto-commit on | Each row is a separate transaction: very slow. Use setAutoCommit(false), addBatch, commit. |
Forgetting rollback() on the error path | The setAutoCommit(true) in finally commits the half-done transaction. |
The run-time lines of the first table were reproduced in a single program:
no table -> [SQLITE_ERROR] SQL error or missing database (no such table: users)
unquoted -> [SQLITE_ERROR] SQL error or missing database (no such column: Ahmet)
apostrophe -> [SQLITE_ERROR] SQL error or missing database (near "s": syntax error)
wrong method -> query does not return ResultSet
index 0 -> column 0 out of bounds [1,3]
index 4 -> column 4 out of bounds [1,3]
UPDATE without WHERE -> 3
DELETE without WHERE -> 3
remaining 0
table still exists -> 1
class: org.sqlite.SQLiteException, code: 1, SQLState: nullThe last line examines the caught exception itself. Its class is org.sqlite.SQLiteException, a subclass of SQLException. getErrorCode() gives SQLite's error code (1, a general SQL error). With most of these mistakes the program compiles and runs; the problem shows up only at run time, and often silently. That is why, after writing JDBC code, you should always check the real contents of the table with DB Browser for SQLite or a SELECT.
11.12Summary
- A database is a persistent, organized, queryable collection of data; a DBMS manages it. Compared with a file, it offers fast search, safe concurrent access, consistency through constraints, column-level permissions (in server DBMSs, for example
GRANTin PostgreSQL or MySQL; in SQLite, access depends on file permissions), and recovery after a failure. - The relational model keeps data in tables: a column is an attribute and a row is a record; a primary key identifies each row uniquely. A table resembles a class, a column a field, and a row an object.
- SQLite is an embedded, serverless, single-file relational database. To use it from Java, the driver jar must be on the classpath; the URL has the form
jdbc:sqlite:sample.db. - The basic SQL statements cover the CRUD operations:
INSERT,SELECT,UPDATE,DELETE.WHEREfilters rows,ORDER BYsorts, andLIMITlimits.UPDATEandDELETEwithoutWHEREaffect all rows. - If no value is given for
INTEGER PRIMARY KEY, SQLite assigns the largestid+ 1;AUTOINCREMENTnever hands out a number that has been used. - Normalization keeps each fact in one place and prevents update, insert, and delete anomalies. Tables are linked with foreign keys; in SQLite, checking is turned on with
PRAGMA foreign_keys = ON. JOIN … ONreturns only matching rows, andLEFT JOINreturns all rows of the left table. IfONis forgotten, a Cartesian product results.GROUP BYgroups rows;WHEREfilters rows before grouping, andHAVINGfilters groups after grouping. Logical order:FROM→WHERE→GROUP BY→HAVING→SELECT→ORDER BY→LIMIT.NULLis an unknown value; it is checked withIS NULL.getIntreturns 0 forNULL; to tell the difference, callwasNull()right afterward.- An index turns a scan into a B-tree search; the cost is that the index must be updated on every write as well.
- The JDBC chain:
DriverManager→Connection→Statement/PreparedStatement→ResultSet. These are interfaces; the driver implements them. executereturns abooleanand is used for table operations,executeUpdatereturns the number of rows affected, andexecuteQueryreturns aResultSet. The result is read withwhile (rs.next()); column numbers start at 1.- User input is never concatenated into the SQL text; it is always passed with
?andsetXxx. Otherwise SQL injection results. - A DAO collects a table's SQL in a single class and returns rows as objects.
- Transaction:
setAutoCommit(false),commit(), and on errorrollback(); all or nothing (ACID). Bulk inserts are done in a single transaction. - Resources are opened with try-with-resources and closed in the order
rs,stmt,conn.SQLExceptionis a checked exception.
11.13Key terms
- database
- relational model
- primary key
- foreign key
- query
- normalization
- join
- aggregate function
- database index
- result set
- prepared statement
- SQL injection
- data access object (DAO)
- transaction
- batch update
- checked exception
- try-with-resources
11.14Test Yourself
The questions use the chapter's three tables: students (Ada 1, Bora 2, Cem 1, Deniz NULL), depts (CS, EE, ME), and orders (Ali 120, Ece 80, Ali 50, Can 200, Ali 30, Ece 40). The answers were verified by running them with JDK 21 and SQLite JDBC.
What does
SELECT COUNT(*) FROM students WHERE dept_id <> 2return?Answer
2. Ada and Cem (1) satisfy the condition; Bora (2) does not. Deniz's
dept_idisNULL, andNULL <> 2is not true but unknown; Deniz is not counted.Three rows (1, 2, 3) are inserted into a table with the column
id INTEGER PRIMARY KEY, the row with number 2 is deleted, and a new row is inserted. What are the numbers in the table?Answer
1, 3, 4. The new row gets the largest
id+ 1 = 4. The gap in the middle is not filled; only if the largest number had been deleted would that number have been reused.What does
SELECT customer, SUM(amount) FROM orders WHERE amount < 100 GROUP BY customer HAVING COUNT(*) >= 2return?Answer
WHEREfirst drops the orders of 120 and 200. Ali's 50 and 30 and Ece's 80 and 40 remain; Can has no orders left. Both groups have a count of 2. The result: Ali 80 and Ece 120.What does
SELECT COUNT(*) FROM depts d LEFT JOIN students s ON s.dept_id = d.idreturn? What ifLEFTis removed?Answer
CS matches two students and EE one; ME matches none, but
LEFT JOINkeeps it with one row: 4. With a plainJOIN, ME drops out: 3. Deniz is in neither query, because the preserved side is the departments.A name search is done with
"SELECT name FROM people WHERE name = '" + input + "'". If the user types' OR 1=1 --, how many rows come back on a table of three people?Answer
The SQL text becomes
SELECT name FROM people WHERE name = '' OR 1=1 --'.--turns the final quotation mark into a comment; the condition is true in every row. 3 rows come back. With aPreparedStatement, 0 rows would come back.The supplies table has stapler 40, scissors 10, and tape 25. The statements
INSERT … ('pen', 5),UPDATE supplies SET stock = stock + 10 WHERE stock < 20, andDELETE FROM supplies WHERE stock > 100are added to aStatementin that order withaddBatch, and thenexecuteBatch()is called. What is the returned array?Answer
[1, 2, 0]. The insert affects one row. In the update, the rows with stock below 20 are scissors (10) and the newly inserted pen (5); they become 20 and 15. There is no row to delete. The
addBatch(String)form ofStatementcan also queue different SQL texts.The
studentstable is read inidorder; for each row,total += rs.getInt("dept_id")is executed, andnone++ifrs.wasNull()is true. At the end, what aretotalandnone?Answer
getIntgives 0 for Deniz: 1 + 2 + 1 + 0 = 4.wasNull()is true only for Deniz:none= 1.The table
members(id INTEGER PRIMARY KEY, email TEXT UNIQUE)is empty.setAutoCommit(false)is called,a@xandb@xare inserted, thenrollback(), thenc@xis inserted, thencommit(). Which rows are in the table?Answer
A single row: (1, c@x).
rollback()undoes the first two inserts; undone inserts do not use up numbers either.c@xis inserted into the empty table and gets 1.
11.15Further reading
- Oracle, The Java Tutorials, "JDBC Database Access": the official, free source that explains connecting, running queries,
PreparedStatement, and transactions with short examples. - SQLite documentation, "Datatypes In SQLite" and "Appropriate Uses For SQLite": explains SQLite's flexible type system and when a server-based database is more suitable.
- OWASP, SQL Injection Prevention Cheat Sheet: describes the kinds of injection and why prepared statements are the primary defense, with examples.
- C. S. Horstmann, Core Java, Volume II: Advanced Features (12th ed.), chapter "Database Programming": a detailed treatment of JDBC, transactions, and advanced features of result sets.
11.16References
- Oracle, The Java Tutorials: JDBC Database Access (Establishing a Connection; Processing SQL Statements with JDBC; Using Prepared Statements; Using Transactions).
- Oracle, Java SE 21 API Documentation: the
java.sqlpackage (DriverManager,Connection,PreparedStatement,ResultSet). - SQLite documentation, sqlite.org: SQL As Understood By SQLite; Datatypes In SQLite; Appropriate Uses For SQLite.
- Xerial, SQLite JDBC Driver, github.com/xerial/sqlite-jdbc.
- P. Deitel and H. Deitel, Java: How to Program, 11th ed., Pearson (Accessing Databases with JDBC).
- C. S. Horstmann, Core Java, Volume II: Advanced Features, 12th ed., Pearson (Database Programming).
- OWASP, SQL Injection Prevention Cheat Sheet.
Related pages: Chapter 11 slides · Study questions · Glossary · © Sercan Külcü. All rights reserved.