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.

Share

Contents

How JDBC works

JDBC separates the API from the implementation. The java.sql package (module java.sql) contains almost only interfaces: Connection, Statement, ResultSet and so on. Each database vendor ships a driver, a JAR whose classes implement those interfaces and speak the database's network protocol. Your code is written against the interfaces, so switching from H2 to PostgreSQL changes the URL and the driver JAR, plus any SQL that is not portable.

A connection starts from a URL such as jdbc:h2:mem:shop or jdbc:postgresql://db:5432/shop. DriverManager offers the URL to each registered driver until one accepts it. Since JDBC 4.0 (Java 6), drivers register themselves: each JAR lists its driver class in META-INF/services/java.sql.Driver, and DriverManager finds it with ServiceLoader. For a server database, the resulting Connection is a TCP connection with an authenticated session behind it, which is why connections are expensive and are normally pooled.

The core JDBC types
TypeRoleBest for
DriverManagerOpens a connection from a URLScripts, tests and tools
DataSourceA configured factory for connectionsApplications; pools such as HikariCP implement it
ConnectionA session with the database; owns transactionsEverything else is created from it
StatementSends a fixed SQL stringDDL and SQL without parameters
PreparedStatementSends SQL with ? parametersAnything with values; see PreparedStatement
CallableStatementCalls stored proceduresSee CallableStatement
ResultSetA cursor over the rows a query returnsReading rows one at a time
JDBC versions that changed everyday code
JDBCJavaNotable addition
4.06Automatic driver loading; no more Class.forName
4.17Resources are AutoCloseable; getObject(column, Class)
4.28java.time types through getObject and setObject; executeLargeUpdate
4.39Sharding 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 DriverManager and with a DataSource, and shows a property of H2's in-memory databases that surprises almost everyone the first time.

Java
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:

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 08001, the class for connection errors. In practice it usually means the driver JAR is missing or the URL has a typo.
  • A new connection starts in auto-commit mode, so every statement is its own transaction, with isolation level 2, which is Connection.TRANSACTION_READ_COMMITTED. Transactions are covered on the transactions and batch page.
  • JdbcDataSource is H2's own DataSource. Code that receives a DataSource does not know or care whether it is a simple one like this or a connection pool, which is why frameworks pass DataSources around rather than URLs.
  • An H2 in-memory database is deleted when its last connection closes. The table created in database c was gone at the next connection, "this database is empty". DB_CLOSE_DELAY=-1 keeps it for the life of the JVM, as database b shows with its row still there.
  • isValid(seconds) checks that a connection still works; on a closed connection it returns false rather than throwing.

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 NULL stock and another a NULL date, because reading NULL correctly is the most common JDBC mistake.

Java
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:

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
  • executeUpdate returns the number of affected rows, 3 here. executeQuery returns a ResultSet positioned before the first row, so next() must be called before reading, and it returns false when there are no more rows.
  • Columns can be read by label ("price") 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.
  • getInt returns 0 for SQL NULL, because an int cannot be null. Only wasNull(), called right after, tells the Notebook's unknown stock apart from a real 0. Alternatively, rs.getObject("stock", Integer.class) returns null.
  • getObject(column, LocalDate.class) maps SQL DATE to java.time directly, avoiding the old java.sql.Date. A NULL date comes back as null.
  • ResultSetMetaData describes the columns: the price is a DECIMAL(10,2), which is why it should be read with getBigDecimal, never getDouble, to keep values like 1.50 exact.

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 and a decimal with a fraction, because the conversions are where data quietly changes.

Java
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:

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 getObject still returns the old java.sql.Date and java.sql.Timestamp for DATE and TIMESTAMP, for backwards compatibility. Asking for LocalDate, LocalDateTime or OffsetDateTime explicitly returns java.time values. TIMESTAMP WITH TIME ZONE keeps its +01:00 offset only through OffsetDateTime.
  • getInt on the DECIMAL 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 with getBigDecimal.
  • getInt on a BIGINT holding 9,000,000,000 failed with SQLState 22003 (numeric value out of range), and on 'abc' with 22018 (invalid character value for cast). Class 22 means a data exception.
  • H2 also maps UUID to java.util.UUID and binary columns to byte[] (printed as [B). Vendor types like these differ most between databases.
  • The column was named dt, not day: H2 2.x treats DAY as a keyword and rejected it as a column name with a syntax error. Reserved words differ between databases and versions, so avoid names like day, user, value and order.

execute, executeUpdate, executeQuery and generated keys

Statement has three ways to run SQL, and they differ in what they return. The program manages a small task table with an auto-increment key, because generated keys are the usual reason to look past executeUpdate.

Java
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:

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
  • executeUpdate returned 0 for CREATE TABLE, 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.
  • Passing Statement.RETURN_GENERATED_KEYS made getGeneratedKeys() return the ids 1, 2 and 3 that the database assigned. Without the flag, the driver need not keep them.
  • executeLargeUpdate (JDBC 4.2) returns a long, for statements that may touch more than about 2.1 billion rows.
  • execute runs any SQL and returns true when the result is a ResultSet; otherwise getUpdateCount() holds the count. Tools that run user-supplied SQL use it, since they cannot know the kind of statement in advance.
  • setMaxRows(5) made the driver stop after 5 of the 1,002 rows. setQueryTimeout limits how long the statement may run. setFetchSize 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.
  • executeQuery on a DELETE threw an exception (H2 code 90002, "method is only allowed for a query").

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.

Java
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:

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 TYPE_FORWARD_ONLY result set, previous() threw an exception. Only next() is allowed.
  • TYPE_SCROLL_INSENSITIVE allowed last(), absolute(2), relative(1) and beforeFirst(). "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.
  • With CONCUR_UPDATABLE, deleteRow() removed Stavanger (the only city under 200,000), updateRow() added 1,000 to the others, and moveToInsertRow() plus insertRow() added Drammen. The driver generated the UPDATE, DELETE and INSERT statements; this only works for simple single-table queries that include the primary key.
  • Updatable result sets are rare in application code; a PreparedStatement with UPDATE is clearer. They are useful in data tools that edit rows on screen.

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.

Java
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:

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 Statement closes its ResultSet, and closing a Connection 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.
  • getSQLState() is a standardized five-character code whose first two characters are the class: 42 for syntax and access errors such as an unknown column, 23 for constraint violations. getErrorCode() is vendor-specific. Check the SQLState class, or the SQLIntegrityConstraintViolationException subclass that drivers such as H2 throw, rather than parsing messages.
  • State 90007 is H2's own code for "object already closed"; codes outside the standard classes differ between databases.
SQLState classes seen on this page
ClassMeaningExample above
08Connection exceptionNo suitable driver
22Data exceptionOut of range, invalid cast
23Integrity constraint violationDuplicate primary key
42Syntax error or access rule violationUnknown column or table

Which API to use

Choosing JDBC APIs
SituationUse
Application codeA pooled DataSource, such as HikariCP
Tests, scripts, one-off toolsDriverManager.getConnection
SQL with any values in itPreparedStatement, never string concatenation
DDL or fixed SQLStatement.execute or executeUpdate
New row idsRETURN_GENERATED_KEYS and getGeneratedKeys()
Nullable numbersgetObject(col, Integer.class), or getInt plus wasNull()
Dates and timesgetObject(col, LocalDate.class) and the other java.time classes
Money and decimalsgetBigDecimal
Many rows in a loopThe default forward-only result set
Several statements that must succeed togetherA transaction; see transactions and batches