JDBC Basics: Connection, Statement & ResultSet
JDBC is Java's standard API for relational databases: the JDK defines the interfaces, and a driver for each database implements them. A Connection is a session with the database, a Statement sends SQL, and a ResultSet is a cursor over the rows that come back. This page explains how the pieces fit, then runs every basic operation against an in-memory H2 database, including the type conversions and NULL handling that cause most JDBC bugs.
Contents
How JDBC works
JDBC separates the API from the implementation. The java.sqljava.sqlConnectionStatementResultSet
A connection starts from a URL such as jdbc:h2:mem:shopjdbc:postgresql://db:5432/shopDriverManagerMETA-INF/services/java.sql.DriverDriverManagerServiceLoaderConnection
| Type | Role | Best for |
|---|---|---|
DriverManager | Opens a connection from a URL | Scripts, tests and tools |
DataSource | A configured factory for connections | Applications; pools such as |
Connection | A session with the database; owns transactions | Everything else is created from it |
Statement | Sends a fixed SQL string | DDL and SQL without parameters |
PreparedStatement | Sends SQL with ? | Anything with values; see |
CallableStatement | Calls stored procedures | See |
ResultSet | A cursor over the rows a query returns | Reading rows one at a time |
| JDBC | Java | Notable addition |
|---|---|---|
| 4.0 | 6 | Automatic driver loading; no more Class.forName |
| 4.1 | 7 | Resources are AutoCloseablegetObject(column, Class) |
| 4.2 | 8 | java.timegetObjectsetObjectexecuteLargeUpdate |
| 4.3 | 9 | Sharding keys, request boundaries for pools |
All examples run on JDK 21 against an in-memory H2 2.3.232 database, so they need only the H2 JAR and every query shown really executed.
Getting a connection
The program lists the registered drivers, asks for a database that has no driver on the classpath, opens connections with DriverManagerDataSource
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Collections;
import java.util.Properties;
import javax.sql.DataSource;
import org.h2.jdbcx.JdbcDataSource;
public class Connecting {
static int count(Connection c) throws SQLException {
try (Statement st = c.createStatement();
ResultSet rs = st.executeQuery("SELECT COUNT(*) FROM note")) {
rs.next();
return rs.getInt(1);
}
}
public static void main(String[] args) throws Exception {
// Drivers found on the classpath through ServiceLoader (JDBC 4.0+)
for (Driver d : Collections.list(DriverManager.getDrivers())) {
System.out.println("registered driver: " + d.getClass().getName() + " "
+ d.getMajorVersion() + "." + d.getMinorVersion());
}
System.out.println("driver for jdbc:h2:... " + DriverManager.getDriver("jdbc:h2:mem:x")
.getClass().getSimpleName());
try {
DriverManager.getConnection("jdbc:postgresql://localhost/shop");
} catch (SQLException e) {
System.out.println("no driver for postgresql: SQLState " + e.getSQLState() + ", "
+ e.getMessage());
}
// 1. DriverManager with user and password, or with a Properties object
Properties props = new Properties();
props.setProperty("user", "sa");
props.setProperty("password", "");
try (Connection c = DriverManager.getConnection("jdbc:h2:mem:a", props)) {
System.out.println("DriverManager: autoCommit=" + c.getAutoCommit() + ", valid="
+ c.isValid(1) + ", isolation=" + c.getTransactionIsolation());
}
// 2. A DataSource: configured once, then asked for connections
JdbcDataSource h2 = new JdbcDataSource();
h2.setURL("jdbc:h2:mem:b;DB_CLOSE_DELAY=-1");
h2.setUser("sa");
DataSource ds = h2;
try (Connection c = ds.getConnection(); Statement st = c.createStatement()) {
st.execute("CREATE TABLE note (txt VARCHAR(20))");
st.execute("INSERT INTO note VALUES ('kept')");
}
try (Connection c = ds.getConnection()) {
System.out.println("DataSource, DB_CLOSE_DELAY=-1: rows after reconnect = "
+ count(c));
}
// Without DB_CLOSE_DELAY, an in-memory database dies with its last connection
try (Connection c = DriverManager.getConnection("jdbc:h2:mem:c", "sa", "");
Statement st = c.createStatement()) {
st.execute("CREATE TABLE note (txt VARCHAR(20))");
}
try (Connection c = DriverManager.getConnection("jdbc:h2:mem:c", "sa", "")) {
count(c);
} catch (SQLException e) {
System.out.println("without DB_CLOSE_DELAY: SQLState " + e.getSQLState() + ", "
+ e.getMessage().substring(0, e.getMessage().indexOf(';')));
}
// A closed connection
Connection closed = ds.getConnection();
closed.close();
System.out.println("closed connection: isClosed=" + closed.isClosed() + ", isValid="
+ closed.isValid(1));
}
}
Output:
registered driver: org.h2.Driver 2.3
driver for jdbc:h2:... Driver
no driver for postgresql: SQLState 08001, No suitable driver found for jdbc:postgresql://localhost/shop
DriverManager: autoCommit=true, valid=true, isolation=2
DataSource, DB_CLOSE_DELAY=-1: rows after reconnect = 1
without DB_CLOSE_DELAY: SQLState 42S04, Table "NOTE" not found (this database is empty)
closed connection: isClosed=true, isValid=false
- The H2 driver registered itself; no code loaded it. A URL no driver accepts gives "No suitable driver found" with SQLState
, the class for connection errors. In practice it usually means the driver JAR is missing or the URL has a typo.08001 - A new connection starts in auto-commit mode, so every statement is its own transaction, with isolation level 2, which is
. Transactions are covered on theConnection.TRANSACTION_READ_COMMITTEDtransactions and batch page . is H2's ownJdbcDataSource . Code that receives aDataSource does not know or care whether it is a simple one like this or a connection pool, which is why frameworks passDataSource s around rather than URLs.DataSource- An H2 in-memory database is deleted when its last connection closes. The table created in database
was gone at the next connection, "this database is empty".c keeps it for the life of the JVM, as databaseDB_CLOSE_DELAY=-1 shows with its row still there.b checks that a connection still works; on a closed connection it returns false rather than throwing.isValid(seconds)
Querying and reading rows
The program connects to an in-memory H2 database, creates a product table and reads it back. The rows were chosen so that one has a NULLNULLNULL
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import java.time.LocalDate;
public class FirstQuery {
public static void main(String[] args) throws Exception {
// In-memory H2 database; the driver registers itself (JDBC 4 service loading)
String url = "jdbc:h2:mem:shop;DB_CLOSE_DELAY=-1";
try (Connection conn = DriverManager.getConnection(url, "sa", "")) {
DatabaseMetaData md = conn.getMetaData();
System.out.println("connected to " + md.getDatabaseProductName() + " "
+ md.getDatabaseProductVersion().split(" ")[0] + " via JDBC "
+ md.getJDBCMajorVersion() + "." + md.getJDBCMinorVersion());
try (Statement st = conn.createStatement()) {
st.execute("""
CREATE TABLE product (
id INT PRIMARY KEY,
name VARCHAR(50) NOT NULL,
price DECIMAL(10,2),
stock INT,
added DATE)""");
int rows = st.executeUpdate("""
INSERT INTO product VALUES
(1, 'Pen', 1.50, 100, DATE '2026-01-10'),
(2, 'Notebook', 4.25, NULL, DATE '2026-01-12'),
(3, 'Stapler', 12.00, 7, NULL)""");
System.out.println("inserted rows: " + rows);
try (ResultSet rs = st.executeQuery(
"SELECT id, name, price, stock, added FROM product ORDER BY id")) {
ResultSetMetaData rsmd = rs.getMetaData();
System.out.println("columns: " + rsmd.getColumnCount() + ", price type "
+ rsmd.getColumnTypeName(3) + "(" + rsmd.getPrecision(3) + ","
+ rsmd.getScale(3) + ")");
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
BigDecimal price = rs.getBigDecimal("price");
int stock = rs.getInt("stock"); // SQL NULL becomes 0 here...
boolean stockNull = rs.wasNull(); // ...so check right after
LocalDate added = rs.getObject("added", LocalDate.class);
System.out.printf(" %d %-9s %6s stock=%-4s added=%s%n", id, name, price,
stockNull ? "NULL" : stock, added);
}
}
}
}
}
}
Output:
connected to H2 2.3.232 via JDBC 4.3
inserted rows: 3
columns: 5, price type DECIMAL(10,2)
1 Pen 1.50 stock=100 added=2026-01-10
2 Notebook 4.25 stock=NULL added=2026-01-12
3 Stapler 12.00 stock=7 added=null
returns the number of affected rows, 3 here.executeUpdate returns aexecuteQuery positioned before the first row, soResultSet must be called before reading, and it returns false when there are no more rows.next()- Columns can be read by label (
) or by 1-based index. Labels are clearer and survive changes to the column order; indexes are slightly faster and are the only option for unnamed expressions."price" returns 0 for SQLgetInt , because anNULL cannot be null. Onlyint , called right after, tells the Notebook's unknown stock apart from a real 0. Alternatively,wasNull() returnsrs.getObject("stock", Integer.class) .null maps SQLgetObject(column, LocalDate.class) toDATE directly, avoiding the oldjava.time . Ajava.sql.Date date comes back asNULL .null describes the columns: the price is aResultSetMetaData , which is why it should be read withDECIMAL(10,2) , nevergetBigDecimal , to keep values like 1.50 exact.getDouble
SQL types and Java types
Every SQL type has a default Java class, and every getter can convert. The table below has one column of each common type, including a value that does not fit in an int
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
public class TypeMapping {
public static void main(String[] args) throws Exception {
try (Connection c = DriverManager.getConnection("jdbc:h2:mem:types", "sa", "");
Statement st = c.createStatement()) {
st.execute("""
CREATE TABLE sample (
i INT, b BIGINT, d DECIMAL(10,2), f DOUBLE PRECISION, s VARCHAR(10),
flag BOOLEAN, dt DATE, ts TIMESTAMP, tz TIMESTAMP WITH TIME ZONE,
u UUID, bin VARBINARY(4))""");
st.execute("""
INSERT INTO sample VALUES (42, 9000000000, 12.99, 0.1, 'abc', TRUE,
DATE '2026-03-01', TIMESTAMP '2026-03-01 14:05:00',
TIMESTAMP WITH TIME ZONE '2026-03-01 14:05:00+01:00',
'123e4567-e89b-12d3-a456-426614174000', X'CAFE')""");
try (ResultSet rs = st.executeQuery("SELECT * FROM sample")) {
rs.next();
ResultSetMetaData md = rs.getMetaData();
System.out.println("column SQL type getObject() returns");
for (int col = 1; col <= md.getColumnCount(); col++) {
Object o = rs.getObject(col);
System.out.printf("%-7s %-25s %s%n", md.getColumnLabel(col),
md.getColumnTypeName(col), o.getClass().getName());
}
// Asking for a specific class (JDBC 4.1+) with java.time types (JDBC 4.2)
System.out.println("getObject(dt, LocalDate): "
+ rs.getObject("dt", LocalDate.class));
System.out.println("getObject(ts, LocalDateTime): "
+ rs.getObject("ts", LocalDateTime.class));
System.out.println("getObject(tz, OffsetDateTime): "
+ rs.getObject("tz", OffsetDateTime.class));
// Conversions the driver performs silently
System.out.println("getInt on DECIMAL 12.99: " + rs.getInt("d"));
System.out.println("getDouble on DOUBLE 0.1: " + rs.getDouble("f")
+ ", getBigDecimal: " + rs.getBigDecimal("f"));
System.out.println("getString on INT: \"" + rs.getString("i") + "\"");
System.out.println("getInt on BIGINT 9000000000:");
try {
System.out.println(" " + rs.getInt("b"));
} catch (SQLException e) {
System.out.println(" SQLException, SQLState " + e.getSQLState());
}
try {
rs.getInt("s");
} catch (SQLException e) {
System.out.println("getInt on VARCHAR 'abc': SQLException, SQLState "
+ e.getSQLState());
}
}
}
}
}
Output:
column SQL type getObject() returns
I INTEGER java.lang.Integer
B BIGINT java.lang.Long
D DECIMAL java.math.BigDecimal
F DOUBLE PRECISION java.lang.Double
S CHARACTER VARYING java.lang.String
FLAG BOOLEAN java.lang.Boolean
DT DATE java.sql.Date
TS TIMESTAMP java.sql.Timestamp
TZ TIMESTAMP WITH TIME ZONE java.time.OffsetDateTime
U UUID java.util.UUID
BIN BINARY VARYING [B
getObject(dt, LocalDate): 2026-03-01
getObject(ts, LocalDateTime): 2026-03-01T14:05
getObject(tz, OffsetDateTime): 2026-03-01T14:05+01:00
getInt on DECIMAL 12.99: 13
getDouble on DOUBLE 0.1: 0.1, getBigDecimal: 0.1
getString on INT: "42"
getInt on BIGINT 9000000000:
SQLException, SQLState 22003
getInt on VARCHAR 'abc': SQLException, SQLState 22018
- Plain
still returns the oldgetObject andjava.sql.Date forjava.sql.Timestamp andDATE , for backwards compatibility. Asking forTIMESTAMP ,LocalDate orLocalDateTime explicitly returnsOffsetDateTime values.java.time keeps itsTIMESTAMP WITH TIME ZONE offset only through+01:00 .OffsetDateTime on thegetInt 12.99 returned 13: H2 rounded. The JDBC specification does not fix how such a conversion rounds, and other drivers may truncate to 12 instead, so rely on neither; read decimals withDECIMAL .getBigDecimal on agetInt holding 9,000,000,000 failed with SQLStateBIGINT (numeric value out of range), and on22003 with'abc' (invalid character value for cast). Class22018 means a data exception.22- H2 also maps
toUUID and binary columns tojava.util.UUID (printed asbyte[] ). Vendor types like these differ most between databases.[B - The column was named
, notdt : H2 2.x treatsday as a keyword and rejected it as a column name with a syntax error. Reserved words differ between databases and versions, so avoid names likeDAY ,day ,user andvalue .order
execute, executeUpdate, executeQuery and generated keys
StatementexecuteUpdate
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class ExecuteVariants {
public static void main(String[] args) throws Exception {
try (Connection c = DriverManager.getConnection("jdbc:h2:mem:exec", "sa", "");
Statement st = c.createStatement()) {
// executeUpdate returns a row count, which is 0 for DDL
System.out.println("CREATE -> " + st.executeUpdate(
"CREATE TABLE task (id INT AUTO_INCREMENT PRIMARY KEY, title VARCHAR(40),"
+ " done BOOLEAN DEFAULT FALSE)"));
// Generated keys: ask for them when executing the INSERT
st.executeUpdate("INSERT INTO task (title) VALUES ('write'), ('test'), ('ship')",
Statement.RETURN_GENERATED_KEYS);
try (ResultSet keys = st.getGeneratedKeys()) {
StringBuilder ids = new StringBuilder();
while (keys.next()) {
ids.append(keys.getLong(1)).append(' ');
}
System.out.println("INSERT -> generated ids " + ids.toString().trim());
}
System.out.println("UPDATE -> " + st.executeUpdate(
"UPDATE task SET done = TRUE WHERE id < 3") + " rows");
System.out.println("UPDATE -> " + st.executeUpdate(
"UPDATE task SET done = TRUE WHERE id = 99") + " rows (no match)");
long deleted = st.executeLargeUpdate("DELETE FROM task WHERE id = 3");
System.out.println("large -> " + deleted + " rows, as a long");
// execute() works for any SQL and says what kind of result it produced
for (String sql : new String[] {"SELECT title FROM task",
"UPDATE task SET done = FALSE"}) {
boolean isQuery = st.execute(sql);
if (isQuery) {
try (ResultSet rs = st.getResultSet()) {
int n = 0;
while (rs.next()) {
n++;
}
System.out.println("execute -> ResultSet with " + n + " rows: " + sql);
}
} else {
System.out.println("execute -> update count " + st.getUpdateCount() + ": "
+ sql);
}
}
// Limits on a statement
st.executeUpdate(
"INSERT INTO task (title) SELECT 'bulk' || X FROM SYSTEM_RANGE(1, 1000)");
st.setMaxRows(5);
st.setQueryTimeout(2); // seconds; 0 means no limit
st.setFetchSize(2); // a hint: rows per round trip
try (ResultSet rs = st.executeQuery("SELECT id FROM task")) {
int n = 0;
while (rs.next()) {
n++;
}
System.out.println("setMaxRows(5): read " + n + " of 1002 rows, fetch size hint "
+ rs.getFetchSize());
}
// executeQuery with a statement that returns no rows fails
try {
st.executeQuery("DELETE FROM task WHERE id = 1");
} catch (java.sql.SQLException e) {
System.out.println("executeQuery(DELETE): SQLState " + e.getSQLState());
}
}
}
}
Output:
CREATE -> 0
INSERT -> generated ids 1 2 3
UPDATE -> 2 rows
UPDATE -> 0 rows (no match)
large -> 1 rows, as a long
execute -> ResultSet with 2 rows: SELECT title FROM task
execute -> update count 2: UPDATE task SET done = FALSE
setMaxRows(5): read 5 of 1002 rows, fetch size hint 0
executeQuery(DELETE): SQLState 90002
returned 0 forexecuteUpdate , 2 for the update that matched two rows, and 0 when nothing matched. Checking that count is how an application detects "not found" on an update, or a lost race in optimistic locking.CREATE TABLE- Passing
madeStatement.RETURN_GENERATED_KEYS return the ids 1, 2 and 3 that the database assigned. Without the flag, the driver need not keep them.getGeneratedKeys() (JDBC 4.2) returns aexecuteLargeUpdate , for statements that may touch more than about 2.1 billion rows.long runs any SQL and returns true when the result is aexecute ; otherwiseResultSet holds the count. Tools that run user-supplied SQL use it, since they cannot know the kind of statement in advance.getUpdateCount() made the driver stop after 5 of the 1,002 rows.setMaxRows(5) limits how long the statement may run.setQueryTimeout is only a hint about how many rows to fetch per network round trip; the result set reported 0, because drivers may ignore it and embedded H2 has no network. H2 also rejects a fetch size larger than the maximum row count.setFetchSize on aexecuteQuery threw an exception (H2 codeDELETE , "method is only allowed for a query").90002
Scrollable and updatable result sets
A result set is forward-only and read-only by default, which is the cheapest kind for the driver. The program uses four cities with populations to move around a scrollable result set, and then to update, delete and insert rows through an updatable one.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Scrollable {
public static void main(String[] args) throws Exception {
try (Connection c = DriverManager.getConnection("jdbc:h2:mem:scroll", "sa", "");
Statement st = c.createStatement()) {
st.execute("CREATE TABLE city (id INT PRIMARY KEY, name VARCHAR(20), pop INT)");
st.execute("INSERT INTO city VALUES (1, 'Oslo', 709000), (2, 'Bergen', 286000),"
+ " (3, 'Trondheim', 212000), (4, 'Stavanger', 145000)");
// The default ResultSet only moves forward
try (ResultSet rs = st.executeQuery("SELECT name FROM city ORDER BY id")) {
System.out.println("default type: " + (rs.getType() == ResultSet.TYPE_FORWARD_ONLY
? "TYPE_FORWARD_ONLY" : rs.getType()));
rs.next();
rs.next();
try {
rs.previous();
} catch (SQLException e) {
System.out.println("previous() on forward-only: SQLState " + e.getSQLState());
}
}
// Scrollable: jump to any row
try (Statement scroll = c.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet rs = scroll.executeQuery("SELECT name FROM city ORDER BY id")) {
rs.last();
System.out.println("last row is #" + rs.getRow() + ": " + rs.getString(1));
rs.absolute(2);
System.out.println("absolute(2): " + rs.getString(1));
rs.relative(1);
System.out.println("relative(1): " + rs.getString(1));
rs.beforeFirst();
rs.next();
System.out.println("after beforeFirst + next: " + rs.getString(1));
}
// Updatable: change rows through the ResultSet
try (Statement upd = c.createStatement(ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_UPDATABLE);
ResultSet rs = upd.executeQuery("SELECT id, name, pop FROM city")) {
while (rs.next()) {
if (rs.getInt("pop") < 200000) {
rs.deleteRow();
} else {
rs.updateInt("pop", rs.getInt("pop") + 1000);
rs.updateRow();
}
}
rs.moveToInsertRow();
rs.updateInt("id", 5);
rs.updateString("name", "Drammen");
rs.updateInt("pop", 102000);
rs.insertRow();
}
try (ResultSet rs = st.executeQuery("SELECT * FROM city ORDER BY id")) {
while (rs.next()) {
System.out.println(" " + rs.getInt(1) + " " + rs.getString(2) + " "
+ rs.getInt(3));
}
}
}
}
}
Output:
default type: TYPE_FORWARD_ONLY
previous() on forward-only: SQLState 90128
last row is #4: Stavanger
absolute(2): Bergen
relative(1): Trondheim
after beforeFirst + next: Oslo
1 Oslo 710000
2 Bergen 287000
3 Trondheim 213000
5 Drammen 102000
- On the default
result set,TYPE_FORWARD_ONLY threw an exception. Onlyprevious() is allowed.next() allowedTYPE_SCROLL_INSENSITIVE ,last() ,absolute(2) andrelative(1) . "Insensitive" means it does not see changes other transactions make after the query ran. To scroll, many drivers hold all rows in client memory, so a scrollable result set over millions of rows can exhaust the heap.beforeFirst()- With
,CONCUR_UPDATABLE removed Stavanger (the only city under 200,000),deleteRow() added 1,000 to the others, andupdateRow() plusmoveToInsertRow() added Drammen. The driver generated theinsertRow() ,UPDATE andDELETE statements; this only works for simple single-table queries that include the primary key.INSERT - Updatable result sets are rare in application code; a
withPreparedStatement is clearer. They are useful in data tools that edit rows on screen.UPDATE
Closing resources and reading errors
Connections, statements and result sets hold resources on both the client and the database server. The program uses a result set after its statement was closed, then triggers two typical SQL errors.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class ClosingResources {
public static void main(String[] args) throws Exception {
String url = "jdbc:h2:mem:demo;DB_CLOSE_DELAY=-1";
// A ResultSet is only usable while its Statement and Connection are open
ResultSet escaped;
try (Connection conn = DriverManager.getConnection(url, "sa", "");
Statement st = conn.createStatement()) {
st.execute("CREATE TABLE t (n INT)");
st.execute("INSERT INTO t VALUES (1), (2)");
escaped = st.executeQuery("SELECT n FROM t");
}
try {
escaped.next();
} catch (SQLException e) {
System.out.println("using a ResultSet after close: SQLException, SQLState "
+ e.getSQLState());
}
// SQLException carries a vendor error code and a standard SQLState
try (Connection conn = DriverManager.getConnection(url, "sa", "");
Statement st = conn.createStatement()) {
st.executeQuery("SELECT missing_column FROM t");
} catch (SQLException e) {
System.out.println("bad column: SQLState " + e.getSQLState() + ", vendor code "
+ e.getErrorCode());
}
try (Connection conn = DriverManager.getConnection(url, "sa", "");
Statement st = conn.createStatement()) {
st.execute("CREATE TABLE u (id INT PRIMARY KEY)");
st.execute("INSERT INTO u VALUES (1)");
st.execute("INSERT INTO u VALUES (1)");
} catch (SQLException e) {
System.out.println("duplicate key: SQLState " + e.getSQLState() + " (class "
+ e.getSQLState().substring(0, 2) + " = integrity constraint violation), "
+ e.getClass().getSimpleName());
}
}
}
Output:
using a ResultSet after close: SQLException, SQLState 90007
bad column: SQLState 42S22, vendor code 42122
duplicate key: SQLState 23505 (class 23 = integrity constraint violation), JdbcSQLIntegrityConstraintViolationException
- Closing a
closes itsStatement , and closing aResultSet closes its statements. Opening all three in try-with-resources, in that order, closes them in reverse order even when an exception occurs. Leaked connections are the most common cause of exhausted connection pools.Connection is a standardized five-character code whose first two characters are the class:getSQLState() for syntax and access errors such as an unknown column,42 for constraint violations.23 is vendor-specific. Check the SQLState class, or thegetErrorCode() subclass that drivers such as H2 throw, rather than parsing messages.SQLIntegrityConstraintViolationException- State
is H2's own code for "object already closed"; codes outside the standard classes differ between databases.90007
| Class | Meaning | Example above |
|---|---|---|
08 | Connection exception | No suitable driver |
22 | Data exception | Out of range, invalid cast |
23 | Integrity constraint violation | Duplicate primary key |
42 | Syntax error or access rule violation | Unknown column or table |
Which API to use
| Situation | Use |
|---|---|
| Application code | A pooled DataSource |
| Tests, scripts, one-off tools | DriverManager.getConnection |
| SQL with any values in it | |
| DDL or fixed SQL | Statement.executeexecuteUpdate |
| New row ids | RETURN_GENERATED_KEYSgetGeneratedKeys() |
| Nullable numbers | getObject(col, Integer.class)getIntwasNull() |
| Dates and times | getObject(col, LocalDate.class)java.time |
| Money and decimals | getBigDecimal |
| Many rows in a loop | The default forward-only result set |
| Several statements that must succeed together | A transaction; see |