Executing SQL with JDBC: Statements, Result Sets and SQL Exceptions
Run SQL with Statement: executeUpdate, executeQuery and execute, reading ResultSet rows with typed getters, column labels, NULL handling and java.time, closing resources, query timeouts and fetch sizes, and analyzing SQLException chains, SQLStates, subclasses and warnings.
kvi5hnuCode Sprout team member12 min readOn this page
Once you have a Connection, you send SQL to the database through statement objects and read query results from result sets. This article covers the plain Statement, the three execute methods, the getters of ResultSet, how to close everything properly, and how JDBC reports errors and warnings.
Plain Statement objects are fine for fixed SQL. As soon as a value from a user or from outside the program ends up in the SQL, use a PreparedStatement instead (article 60). That is not optional. It's the defense against SQL injection.
Executing statements
try (Statement stat = conn.createStatement()) {
int count = stat.executeUpdate("UPDATE products SET price = price * 1.1 WHERE supplier_id = 'NORD'");
try (ResultSet rs = stat.executeQuery("SELECT name, price FROM products ORDER BY name")) {
while (rs.next()) { ... }
}
}
There are three methods, depending on what the SQL produces:
executeUpdate(sql)is forINSERT,UPDATE,DELETEand DDL such asCREATE TABLE. It returns the number of affected rows, or 0 for statements without a row count.executeLargeUpdate(Java 8) returns alongfor very large changes.executeQuery(sql)is forSELECTand returns aResultSet.execute(sql)runs anything. It returnstrueif the first result is a result set, which you get withgetResultSet(), andfalseif it's an update count, which you get withgetUpdateCount(). Use it for SQL whose kind you don't know in advance, such as statements typed by a user or read from a script. Article 61 shows how to walk through several results.
The specification says that calling executeQuery with an UPDATE, or executeUpdate with a SELECT, throws an SQLException. Most drivers, H2 and PostgreSQL included, do, though a few are lenient. Don't rely on either behavior: use execute when you don't know what the SQL produces.
Statement settings
| Method | Effect |
|---|---|
setQueryTimeout(seconds) | cancel statements that run longer, failing with SQLTimeoutException |
cancel() | cancel a running statement from another thread |
setMaxRows(n), setLargeMaxRows(n) | return at most n rows |
setFetchSize(n) | a hint for how many rows to fetch per network round trip |
closeOnCompletion() | close the statement when its last result set closes (Java 7) |
Fetch size matters for large results. Some drivers read the entire result into memory by default. PostgreSQL does that unless auto-commit is off and a fetch size is set, and MySQL streams only with special settings. With a suitable fetch size, the driver fetches rows in batches as you call next().
Reading a ResultSet
A result set is a cursor over the result rows. It starts before the first row, and each next() call moves to the next row. next() returns false when there are no more rows. There's no hasNext:
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString(2);
BigDecimal price = rs.getBigDecimal("price");
}
- Every getter comes in two forms: one takes a column number, starting at 1, and the other a column label. The label is the alias from
AS, or the column name if there's none. Labels are matched case-insensitively. Numbers are slightly faster, and labels are clearer and survive changes in column order.findColumn(label)converts a label to a number. - There are getters for every common type:
getInt,getLong,getDouble,getBigDecimal,getString,getBoolean,getBytes,getDate,getTimestamp,getObject, and more. Drivers convert where reasonable.getStringworks on almost any column, whilegetInton a column that contains "Hammer" fails with a data exception (SQLState22018in H2). - For dates and times, use
getObject(column, LocalDate.class), likewise withLocalTime,LocalDateTimeandOffsetDateTime(JDBC 4.2). The oldjava.sql.Date,TimeandTimestampclasses are only needed for legacy code (see the Date and Time part, article 70). - Calling a getter before
next(), or afternext()returnedfalse, throws anSQLException, because there is no current row.
NULL values
A SQL NULL comes back as null from getters that return objects (getString, getBigDecimal, getObject). The primitive getters can't return null, so getInt and getDouble return 0 and getBoolean returns false. To tell a stored zero from a missing value, call wasNull() right after the getter, or use getObject(column, Integer.class), which returns null.
Reading rows with H2
This program reads a table that has a row with NULL values:
import java.math.BigDecimal;
import java.sql.*;
import java.time.LocalDate;
public class Reading {
public static void main(String[] args) throws SQLException {
try (Connection conn = DriverManager.getConnection("jdbc:h2:mem:shop");
Statement stat = conn.createStatement()) {
stat.executeUpdate("CREATE TABLE products (product_id INTEGER PRIMARY KEY, name VARCHAR(20), price DECIMAL(8,2), added DATE)");
stat.executeUpdate("INSERT INTO products VALUES (1, 'Hammer', 12.50, DATE '2026-03-01'), (3, 'Gift card', NULL, NULL)");
try (ResultSet rs = stat.executeQuery("SELECT product_id AS id, name, price, added FROM products ORDER BY id")) {
while (rs.next()) {
int id = rs.getInt("id"); // the label from AS
String name = rs.getString(2);
BigDecimal price = rs.getBigDecimal("price"); // null for SQL NULL
double priceAsDouble = rs.getDouble("price"); // 0.0 for SQL NULL...
boolean priceWasNull = rs.wasNull(); // ...so ask
LocalDate added = rs.getObject("added", LocalDate.class); // java.time support
String priceAsText = rs.getString("price"); // conversions
System.out.printf("%d %s price=%s (double %s, wasNull %b, text %s) added=%s%n",
id, name, price, priceAsDouble, priceWasNull, priceAsText, added);
}
System.out.println("column of 'NAME': " + rs.findColumn("NAME"));
}
ResultSet first = stat.executeQuery("SELECT 1");
stat.executeQuery("SELECT 2");
System.out.println("first result set closed by the next query: " + first.isClosed());
try (ResultSet rs = stat.executeQuery("SELECT name FROM products")) {
rs.next();
rs.getInt(1);
} catch (SQLException e) {
System.out.println(e.getClass().getSimpleName() + " " + e.getSQLState());
}
try (ResultSet rs = stat.executeQuery("SELECT name FROM products")) {
rs.getString(1);
} catch (SQLException e) {
System.out.println("before next(): " + e.getSQLState());
}
}
}
}
Output with H2 2.3:
1 Hammer price=12.50 (double 12.5, wasNull false, text 12.50) added=2026-03-01
3 Gift card price=null (double 0.0, wasNull true, text null) added=null
column of 'NAME': 2
first result set closed by the next query: true
JdbcSQLDataException 22018
before next(): 02000
The exception classes like JdbcSQLDataException are H2's own subclasses of the standard JDBC exceptions described below.
Managing connections, statements and result sets
- A connection can create many statements, and a statement can run many SQL commands one after another. But a statement has at most one open result set: executing another command on the same statement closes the previous result set, as the output above shows. To work with two results at once, use two statements. Often a single query with a join is better anyway.
- Closing a statement closes its result set, and closing a connection closes its statements. Still, close each object as soon as you're done, because they hold memory and cursors on the server. Try-with-resources makes that automatic. A connection that lives long, such as one from a pool, must not accumulate open statements.
- JDBC objects aren't meant to be shared between threads. Give each thread, or each unit of work, its own connection from a pool.
SQL exceptions
Almost every JDBC method can throw the checked SQLException. Besides the message, it carries:
getSQLState(): a five-character code standardized by SQL (ISO/ANSI) and X/Open. The first two characters are the class, for example23for integrity constraint violations,22for data errors,42for syntax and access errors,08for connection problems and40for transaction rollbacks such as deadlocks. Vendors add their own codes within these classes.getErrorCode(): the database vendor's own error number.- The usual cause chain (
getCause()), and additionally a chain of next exceptions (getNextException()). A driver uses the latter to report several errors at once, for example from a batch.
SQLException implements Iterable<Throwable>. A simple for (Throwable t : e) visits the first exception, its causes, then the next exception and its causes, and so on. That's the easiest way to log everything.
The exception hierarchy
Drivers throw subclasses that let you react to a category of error without parsing SQLStates:

SQLNonTransientExceptionmeans retrying the same operation will fail again until something changes. Its subclasses cover data errors, unsupported features, constraint violations, failed logins, broken connections and syntax errors.SQLTransientExceptionmeans the operation might succeed if retried, perhaps after a pause. Examples are timeouts, a transaction chosen as a deadlock victim (SQLState class40) and temporary connection problems.SQLRecoverableExceptionmeans the operation may succeed if the application recovers first, at a minimum by closing the connection and opening a new one.
For example, catch (SQLIntegrityConstraintViolationException e) handles a duplicate key, such as a user name that's already taken, independently of the database. Not every driver maps every error to the best subclass, so check the SQLState too.
Errors from H2
The following program executes the statements in a script one by one with execute, prints result sets with the help of metadata (article 64) and update counts, and reports errors. The script creates and fills two tables, then deliberately triggers three failures:
-- suppliers and products for the examples
CREATE TABLE suppliers (supplier_id CHAR(4) PRIMARY KEY, name VARCHAR(40) NOT NULL, country VARCHAR(30));
CREATE TABLE products (product_id INTEGER PRIMARY KEY, name VARCHAR(20) NOT NULL,
supplier_id CHAR(4) REFERENCES suppliers(supplier_id), price DECIMAL(8,2), added DATE);
INSERT INTO suppliers VALUES ('ACME', 'Acme Tools', 'USA'), ('NORD', 'Nordic Wood', 'Sweden');
INSERT INTO products VALUES (1, 'Hammer', 'ACME', 12.50, DATE '2026-03-01'),
(2, 'Oak shelf', 'NORD', 89.90, DATE '2026-05-17'), (3, 'Gift card', NULL, NULL, NULL);
SELECT * FROM products ORDER BY product_id;
UPDATE products SET price = price * 1.1 WHERE supplier_id = 'NORD';
INSERT INTO products VALUES (1, 'Saw', 'ACME', 20.00, NULL);
INSERT INTO products VALUES (4, 'Extra long product name', 'ACME', 1.00, NULL);
SELEC * FROM products;
SELECT name, price FROM products WHERE price > 50;
import java.nio.file.*;
import java.sql.*;
import java.util.*;
public class SqlRunner {
public static void main(String[] args) throws Exception {
String script = Files.readString(Path.of(args[0]));
try (Connection conn = DriverManager.getConnection("jdbc:h2:mem:shop");
Statement stat = conn.createStatement()) {
for (String sql : script.split(";\\s*\n")) { // one statement per ";" at a line end
sql = sql.lines().filter(l -> !l.startsWith("--")).reduce("", (a, b) -> a + " " + b.strip()).strip();
if (sql.isEmpty()) continue;
System.out.println("> " + (sql.length() > 60 ? sql.substring(0, 57) + "..." : sql));
try {
if (stat.execute(sql)) {
try (ResultSet rs = stat.getResultSet()) { print(rs); }
} else {
System.out.println(" " + stat.getUpdateCount() + " row(s) affected");
}
} catch (SQLException e) {
System.out.println(" " + e.getClass().getSimpleName() + " SQLState=" + e.getSQLState()
+ " vendorCode=" + e.getErrorCode());
}
}
}
}
static void print(ResultSet rs) throws SQLException {
ResultSetMetaData meta = rs.getMetaData();
int n = meta.getColumnCount();
var header = new StringJoiner(" | ", " ", "");
for (int i = 1; i <= n; i++) header.add(meta.getColumnLabel(i));
System.out.println(header);
while (rs.next()) {
var row = new StringJoiner(" | ", " ", "");
for (int i = 1; i <= n; i++) row.add(String.valueOf(rs.getObject(i)));
System.out.println(row);
}
}
}
Output of java -cp h2-2.3.232.jar:. SqlRunner shop.sql:
> CREATE TABLE suppliers (supplier_id CHAR(4) PRIMARY KEY, ...
0 row(s) affected
> CREATE TABLE products (product_id INTEGER PRIMARY KEY, na...
0 row(s) affected
> INSERT INTO suppliers VALUES ('ACME', 'Acme Tools', 'USA'...
2 row(s) affected
> INSERT INTO products VALUES (1, 'Hammer', 'ACME', 12.50, ...
3 row(s) affected
> SELECT * FROM products ORDER BY product_id
PRODUCT_ID | NAME | SUPPLIER_ID | PRICE | ADDED
1 | Hammer | ACME | 12.50 | 2026-03-01
2 | Oak shelf | NORD | 89.90 | 2026-05-17
3 | Gift card | null | null | null
> UPDATE products SET price = price * 1.1 WHERE supplier_id...
1 row(s) affected
> INSERT INTO products VALUES (1, 'Saw', 'ACME', 20.00, NULL)
JdbcSQLIntegrityConstraintViolationException SQLState=23505 vendorCode=23505
> INSERT INTO products VALUES (4, 'Extra long product name'...
JdbcSQLDataException SQLState=22001 vendorCode=22001
> SELEC * FROM products
JdbcSQLSyntaxErrorException SQLState=42001 vendorCode=42001
> SELECT name, price FROM products WHERE price > 50
NAME | PRICE
Oak shelf | 98.89
The unquoted names were stored in upper case, as the SQL standard requires (PostgreSQL uses lower case instead). A duplicate key gives 23505, a value that's too long 22001 and a syntax error 42001. The other statements were unaffected. Real databases also ship command-line tools that run scripts like this, but each has its own rules for statement separators.
Warnings
Problems that don't stop an operation, such as a value that was rounded or a deprecated syntax, are reported as warnings. SQLWarning extends SQLException but is never thrown. Connections, statements and result sets collect warnings, which you read with getWarnings() and follow with getNextWarning():
for (SQLWarning w = stat.getWarnings(); w != null; w = w.getNextWarning())
System.out.println(w.getSQLState() + " " + w.getMessage());
stat.clearWarnings();
Warnings for a statement are cleared each time it executes again. DataTruncation (SQLState 01004) is a warning that a value was cut off while reading. When truncation happens while writing, the driver throws the DataTruncation (SQLState 22001) instead. Its methods tell which column or parameter was affected and how many bytes were expected and transferred. PostgreSQL also delivers RAISE NOTICE messages from stored procedures as warnings.
The program
The runnable demo does without a database. The reading part runs ordinary ResultSet code against a CachedRowSet (article 63) filled with three products, one of which has a NULL price. The second part maps typical SQLStates to the standard exception subclasses (as drivers do) and asks whether each one is transient. The third builds an exception chain with a cause and walks it with an enhanced for loop, and the last part chains two warnings, including a DataTruncation.
import java.io.IOException;
import java.math.BigDecimal;
import java.sql.*;
import java.util.*;
import javax.sql.RowSetMetaData;
import javax.sql.rowset.*;
public class Solution {
// Builds an in-memory ResultSet (a CachedRowSet) so that the reading code below is real JDBC code
static ResultSet products() throws SQLException {
CachedRowSet rs = RowSetProvider.newFactory().createCachedRowSet();
RowSetMetaData meta = new RowSetMetaDataImpl();
meta.setColumnCount(3);
meta.setColumnName(1, "ID"); meta.setColumnLabel(1, "ID"); meta.setColumnType(1, Types.INTEGER);
meta.setColumnName(2, "NAME"); meta.setColumnLabel(2, "NAME"); meta.setColumnType(2, Types.VARCHAR);
meta.setColumnName(3, "PRICE"); meta.setColumnLabel(3, "PRICE"); meta.setColumnType(3, Types.DECIMAL);
rs.setMetaData(meta);
Object[][] rows = { { 1, "Hammer", new BigDecimal("12.50") }, { 2, "Oak shelf", new BigDecimal("89.90") }, { 3, "Gift card", null } };
for (Object[] row : rows) {
rs.moveToInsertRow();
rs.updateInt(1, (Integer) row[0]);
rs.updateString(2, (String) row[1]);
if (row[2] == null) rs.updateNull(3); else rs.updateBigDecimal(3, (BigDecimal) row[2]);
rs.insertRow();
}
rs.moveToCurrentRow();
rs.beforeFirst();
return rs;
}
// Maps the SQLState class (first two characters) to the matching standard subclass
static SQLException classify(String reason, String sqlState, int vendorCode) {
return switch (sqlState.substring(0, 2)) {
case "08" -> new SQLNonTransientConnectionException(reason, sqlState, vendorCode);
case "0A" -> new SQLFeatureNotSupportedException(reason, sqlState, vendorCode);
case "22" -> new SQLDataException(reason, sqlState, vendorCode);
case "23" -> new SQLIntegrityConstraintViolationException(reason, sqlState, vendorCode);
case "28" -> new SQLInvalidAuthorizationSpecException(reason, sqlState, vendorCode);
case "40" -> new SQLTransactionRollbackException(reason, sqlState, vendorCode);
case "42" -> new SQLSyntaxErrorException(reason, sqlState, vendorCode);
default -> new SQLException(reason, sqlState, vendorCode);
};
}
public static void main(String[] args) throws SQLException {
System.out.println("--- reading a result set ---");
try (ResultSet rs = products()) {
System.out.println("before next(): isBeforeFirst=" + rs.isBeforeFirst());
while (rs.next()) {
int id = rs.getInt(1); // column numbers start at 1
String name = rs.getString("NAME");
BigDecimal price = rs.getBigDecimal("PRICE");
double asDouble = rs.getDouble("PRICE");
boolean wasNull = rs.wasNull();
String asText = rs.getString("PRICE"); // converted to a string
System.out.printf("%d %-9s price=%s double=%s wasNull=%b text=%s%n", id, name, price, asDouble, wasNull, asText);
}
System.out.println("after the loop: isAfterLast=" + rs.isAfterLast() + ", findColumn(\"PRICE\")=" + rs.findColumn("PRICE"));
try {
rs.getString("COLOR");
} catch (SQLException e) {
System.out.println("unknown column: " + e.getMessage());
}
}
System.out.println("--- the SQLException hierarchy ---");
String[][] errors = {
{ "duplicate key value violates unique constraint", "23505" },
{ "value too long for type varchar(20)", "22001" },
{ "syntax error at or near \"SELEC\"", "42601" },
{ "deadlock detected", "40P01" },
{ "connection refused", "08001" },
{ "password authentication failed", "28P01" },
{ "feature not supported", "0A000" },
{ "disk full", "53100" },
};
for (String[] e : errors) {
SQLException ex = classify(e[0], e[1], 0);
String kind = ex instanceof SQLTransientException ? "transient (retry may work)"
: ex instanceof SQLNonTransientException ? "non-transient" : "unclassified";
System.out.printf("%s %-41s %s%n", e[1], ex.getClass().getSimpleName(), kind);
}
System.out.println("--- chained exceptions and causes ---");
SQLException first = new SQLIntegrityConstraintViolationException("row 3: duplicate key", "23505", 1);
SQLException second = new SQLDataException("row 7: value too long", "22001", 2, new IOException("network trace: frame 42"));
first.setNextException(second);
first.setNextException(new SQLSyntaxErrorException("row 9: unknown column", "42703", 3));
for (Throwable t : first) // walks causes and the next-exception chain
System.out.println(t.getClass().getSimpleName() + ": " + t.getMessage()
+ (t instanceof SQLException s ? " [" + s.getSQLState() + "]" : ""));
int count = 0;
for (SQLException e = first; e != null; e = e.getNextException()) count++;
System.out.println("next-exception chain length: " + count);
System.out.println("--- warnings ---");
SQLWarning warnings = new SQLWarning("price rounded to two decimals", "01000");
warnings.setNextWarning(new DataTruncation(2, false, true, 30, 20)); // column 2, read, 30 -> 20 bytes
for (SQLWarning w = warnings; w != null; w = w.getNextWarning()) {
System.out.print(w.getClass().getSimpleName() + " [" + w.getSQLState() + "] " + w.getMessage());
if (w instanceof DataTruncation dt)
System.out.print(" index=" + dt.getIndex() + " parameter=" + dt.getParameter()
+ " read=" + dt.getRead() + " size " + dt.getDataSize() + " -> " + dt.getTransferSize());
System.out.println();
}
System.out.println("SQLWarning is an SQLException: " + (warnings instanceof SQLException));
}
}
--- reading a result set ---
before next(): isBeforeFirst=true
1 Hammer price=12.50 double=12.5 wasNull=false text=12.50
2 Oak shelf price=89.90 double=89.9 wasNull=false text=89.90
3 Gift card price=null double=0.0 wasNull=true text=null
after the loop: isAfterLast=true, findColumn("PRICE")=3
unknown column: Invalid column name
--- the SQLException hierarchy ---
23505 SQLIntegrityConstraintViolationException non-transient
22001 SQLDataException non-transient
42601 SQLSyntaxErrorException non-transient
40P01 SQLTransactionRollbackException transient (retry may work)
08001 SQLNonTransientConnectionException non-transient
28P01 SQLInvalidAuthorizationSpecException non-transient
0A000 SQLFeatureNotSupportedException non-transient
53100 SQLException unclassified
--- chained exceptions and causes ---
SQLIntegrityConstraintViolationException: row 3: duplicate key [23505]
SQLDataException: row 7: value too long [22001]
IOException: network trace: frame 42
SQLSyntaxErrorException: row 9: unknown column [42703]
next-exception chain length: 3
--- warnings ---
SQLWarning [01000] price rounded to two decimals
DataTruncation [01004] Data truncation index=2 parameter=false read=true size 30 -> 20
SQLWarning is an SQLException: true
The demo maps class 08 to the non-transient subclass. A driver can just as well choose SQLTransientConnectionException for a connection problem that might go away.
Common questions
Can I get columns by name instead of by index?
Yes: rs.getString("name"). Names are case-insensitive. If a query returns two columns with the same name (common in joins), the first one wins; give them aliases with AS. Index access is slightly faster but more fragile when the query changes.
How do I count the rows in a ResultSet?
You can't without reading them all. Ask the database instead (SELECT COUNT(*) ...), or collect the rows into a list while iterating and use its size. Scrollable result sets (article 62) can jump to the last row, but that is driver-dependent and often expensive.
Can I return a ResultSet from a method?
Not safely, because it becomes invalid when its statement or connection closes. Map the rows into objects or records inside the method, while the resources are still open, and return those. Article 63's CachedRowSet is the alternative when a disconnected result is needed.
How do I map a row to a Java record?
Read each column and call the constructor: new Product(rs.getInt("id"), rs.getString("name"), rs.getBigDecimal("price")). A small helper method or lambda (RowMapper-style) keeps this in one place. Libraries like Spring's JdbcClient or jOOQ automate it.
Why do I get "ResultSet closed" errors? The statement that produced it was closed or re-executed, or the connection was closed. A statement has at most one open result set by default; executing it again closes the previous one. Use separate statements for nested queries.
Which exception should I catch for a duplicate key?
SQLIntegrityConstraintViolationException, and check the SQLState 23505 (unique violation) to be specific, since the same class covers foreign key (23503) and NOT NULL (23502) violations.
API reference
| API | Purpose |
|---|---|
Connection.createStatement() | create a statement for SQL without parameters |
Statement.executeUpdate(sql), executeLargeUpdate(sql) | run INSERT, UPDATE, DELETE or DDL, return the row count |
Statement.executeQuery(sql) | run a query, return a ResultSet |
Statement.execute(sql), getResultSet(), getUpdateCount() | run any SQL and fetch its result |
setQueryTimeout, cancel, setMaxRows, setFetchSize, closeOnCompletion | statement settings |
ResultSet.next(), getXxx(index), getXxx(label), getObject(col, type) | iterate and read values |
ResultSet.wasNull(), findColumn(label), isClosed() | NULL checks, column numbers, state |
SQLException.getSQLState(), getErrorCode(), getNextException(), iterator() | error details and chains |
SQLNonTransientException, SQLTransientException, SQLRecoverableException and subclasses | error categories |
getWarnings(), clearWarnings(), SQLWarning.getNextWarning(), DataTruncation | warnings |
Summary
- Use
executeUpdatefor changes and DDL (returns a row count),executeQueryfor SELECT, andexecutewhen you don't know which. - A
ResultSetstarts before the first row. Loop withwhile (rs.next()), read columns by label or by 1-based number, and usegetObject(col, LocalDate.class)for dates. - SQL
NULLisnullfor object getters but0orfalsefor primitive getters, so check withwasNull(). - One open result set per statement. Close result sets, statements and connections with try-with-resources.
SQLExceptioncarries an SQLState, a vendor code, causes and a chain of next exceptions. Iterate over it to see everything, and catch the subclasses to handle categories such as constraint violations or transient failures. Warnings are collected, not thrown.
Practice Questions
Why does rs.getString(1) throw an exception right after executeQuery, even though the query returned rows?
A result set starts positioned before the first row. You must call rs.next() once to move to the first row before reading any column.
The stock column is NULL for some products. What do rs.getInt("stock") and rs.getObject("stock", Integer.class) return for those rows?
getInt returns 0, because a primitive can't be null. You'd have to call rs.wasNull() to find out that the value was really NULL. getObject("stock", Integer.class) returns null, so you can tell the two cases apart directly.
You loop over customers with one Statement and, inside the loop, run a query for each customer's orders on the same Statement. The outer loop stops after the first customer. Why?
A statement has only one open result set. Executing the inner query closed the outer result set, so the next next() fails or returns false. Use a second statement for the inner query, or better, a single query that joins customers and orders.
How can you report a "user name already taken" error without depending on a particular database's error codes?
Check getSQLState(): class 23 means an integrity constraint violation, and 23505 specifically a unique violation (class 23 also covers NOT NULL and foreign key violations). Catching SQLIntegrityConstraintViolationException also works with drivers that use the standard subclasses (H2, MySQL, Oracle), but not with the PostgreSQL driver, which throws its own plain SQLException subclass, so test the SQLState as well. The vendor error code from getErrorCode() differs between databases.
A transaction fails with SQLState 40001 (serialization failure) or 40P01 (deadlock). Should the program show an error or retry?
Class 40 means the database rolled back the transaction to resolve a conflict with another one. Many drivers report it as SQLTransactionRollbackException, a subclass of SQLTransientException; others, such as PostgreSQL's, only set the SQLState, so check for class 40. Retrying the whole transaction (not just the last statement), perhaps after a short random delay, will usually succeed. Show an error only after several failed attempts.
Previous: Connecting to a Database with JDBC: URLs, Drivers, DriverManager and DataSource
Next: Prepared Statements in JDBC: Parameters, Reuse and Preventing SQL Injection
Related reading
- Java Logging Handlers, Filters and Formatters: Configuring java.util.logging
- Java Logging Basics: System.Logger and java.util.logging
- Java Assertions: Using assert, Enabling Assertions and Design by Contract
- Java Exception Handling Best Practices: Tips Every Developer Should Know
- Java finally and try-with-resources: Cleaning Up and Reading Stack Traces

More in Core Java II
FFM Upcalls, Variadic Functions and errno
Advanced FFM calls: passing Java code to C as function pointers with upcall stubs, binding objects and lambdas, calling variadic functions such as printf, capturing errno and GetLastError, and a C library that calls back into Java. The final article of the course.
Calling Foreign Functions: Linker, Symbol Lookup, Downcalls and jextract
Calling C functions from pure Java with the FFM API: the native linker, default, library and loader symbol lookups, function descriptors, downcall handles, invokeExact, pointers and NULL, struct results, critical calls, enabling native access, and generating bindings with jextract.
FFM Memory Layouts: Structs, Unions, Sequences and Var Handles
Describing C data with FFM memory layouts: value layouts and C types, struct and union layouts, alignment and padding, sequences, layout paths, var handles with base offsets, offset and slice handles, pointers with target layouts, and atomic access modes.
Foreign Function and Memory API: Arenas and Memory Segments
Getting started with the FFM API (final since Java 22): a first foreign call, confined, shared, automatic and global arenas, native and heap memory segments, reading and writing values, C strings and arrays, alignment and byte order, slices, copies, allocators, and memory-mapped files.
Discussion
Sign in to ask a question or share what you learned.