CallableStatement, Stored Procedures & ResultSet Metadata

A stored procedure is logic stored and executed inside the database. JDBC calls it through CallableStatement, using an escape syntax that each driver translates into its database's own call syntax. This page explains when procedures are worth it, runs calls, escapes, transactions and errors on H2, and uses metadata to describe procedures and arbitrary result sets at run time.

Share

Contents

What stored procedures are, and how JDBC calls them

A stored procedure is a named piece of code that lives in the database and runs there. Calling it sends one short request instead of several queries, so the data does not travel to the application and back. Procedures are also a security tool: a user can be allowed to execute a procedure without having direct access to the tables it changes. The costs are real too: procedure code is written in a vendor language (PL/pgSQL, PL/SQL, T-SQL), is harder to version, test and debug than application code, and ties the application to one database.

Procedures have three kinds of parameters. IN parameters pass values in, OUT parameters return values, and IN OUT parameters do both. A procedure can also return a result set, and a function has a single return value. JDBC models all of this with CallableStatement, a subinterface of PreparedStatement, and a portable escape syntax in curly braces that the driver rewrites for its database.

The CallableStatement API
Method or syntaxSincePurpose
conn.prepareCall("{call p(?, ?)}")JDBC 1Call a procedure
"{? = call f(?)}"JDBC 1Call a function; the first ? is the return value
registerOutParameter(index, Types.X)JDBC 1Declare an OUT or IN OUT parameter, or the return value
getBigDecimal(index) and other gettersJDBC 1Read OUT values after execute()
setInt("name", ...), getInt("name")JDBC 3.0Named parameters, where the driver supports them
getObject(index, Class)JDBC 4.1Typed OUT values, including java.time
executeQuery(), getMoreResults()JDBC 1Procedures that return one or several result sets

H2 2.3, used on JDK 21 so the examples run anywhere, implements procedures as public static Java methods registered with CREATE ALIAS. The JDBC calls are the same as for other databases, but H2 has no OUT parameters other than the return value, so those are described in a table later rather than run.

Calling functions and procedures

The program registers two procedures, one that returns a single value (a price with tax) and one that returns rows (products low on stock), and calls both. The threshold of 10 was chosen so that two of the four products qualify.

Java
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;

public class Procedures {

    // H2 implements stored procedures as public static Java methods registered with CREATE ALIAS
    public static BigDecimal priceWithTax(BigDecimal net, BigDecimal ratePercent) {
        return net.multiply(BigDecimal.ONE.add(ratePercent.movePointLeft(2)))
                .setScale(2, RoundingMode.HALF_UP);
    }

    // A procedure that returns rows: H2 passes the caller's connection as the first argument
    public static ResultSet lowStock(Connection conn, int threshold) throws SQLException {
        var ps = conn.prepareStatement(
                "SELECT name, stock FROM product WHERE stock < ? ORDER BY stock");
        ps.setInt(1, threshold);
        return ps.executeQuery();
    }

    public static void main(String[] args) throws Exception {
        try (Connection c = DriverManager.getConnection("jdbc:h2:mem:procs", "sa", "");
             Statement st = c.createStatement()) {
            st.execute("CREATE TABLE product (name VARCHAR(20), stock INT)");
            st.execute("INSERT INTO product VALUES ('pen', 120), ('pad', 8), ('clip', 3), "
                    + "('ink', 15)");
            st.execute("CREATE ALIAS PRICE_WITH_TAX FOR 'Procedures.priceWithTax'");
            st.execute("CREATE ALIAS LOW_STOCK FOR 'Procedures.lowStock'");

            // JDBC escape syntax: {? = call name(...)} for a function with a return value
            try (CallableStatement cs = c.prepareCall("{? = call PRICE_WITH_TAX(?, ?)}")) {
                cs.registerOutParameter(1, Types.DECIMAL);
                cs.setBigDecimal(2, new BigDecimal("19.99"));
                cs.setBigDecimal(3, new BigDecimal("25"));
                cs.execute();
                System.out.println("19.99 + 25% tax = " + cs.getBigDecimal(1));
            }

            // {call name(...)} for a procedure that returns a result set
            try (CallableStatement cs = c.prepareCall("{call LOW_STOCK(?)}")) {
                cs.setInt(1, 10);
                try (ResultSet rs = cs.executeQuery()) {
                    while (rs.next()) {
                        System.out.println("low stock: " + rs.getString(1) + " ("
                                + rs.getInt(2) + ")");
                    }
                }
            }

            // Procedures registered this way are visible in the database's metadata
            try (ResultSet rs = c.getMetaData().getProcedures(null, "PUBLIC", "%")) {
                while (rs.next()) {
                    System.out.println("procedure in metadata: " + rs.getString("PROCEDURE_NAME"));
                }
            }
        }
    }
}

Output:

Output
19.99 + 25% tax = 24.99
low stock: clip (3)
low stock: pad (8)
procedure in metadata: LOW_STOCK
procedure in metadata: PRICE_WITH_TAX
  • {? = call NAME(?, ?)} is the JDBC escape syntax for a function with a return value. The first ? is the return value, declared with registerOutParameter and read after execute(). 19.99 plus 25% is 24.9875, rounded to 24.99. The parameter indexes count the return value, so the inputs are 2 and 3.
  • {call NAME(?)} calls a procedure. When it returns rows, read them with executeQuery() like any query. Only the clip (3) and the pad (8) are below 10.
  • H2 passes the caller's Connection as the first Java argument of lowStock, so the procedure can run SQL. That argument does not appear in the SQL call.
  • DatabaseMetaData.getProcedures lists the procedures the database knows, which is useful for tools and for checking that a migration created them.

The JDBC escape syntax

The curly braces are not SQL. They are JDBC escapes, which the driver translates before the database sees the statement. Connection.nativeSQL shows the translation without running anything. The program tries the two call forms and two other escapes, scalar functions ({fn ...}) and date literals ({d ...}), and then uses the tax function directly in a query.

Java
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;

public class EscapeSyntax {

    public static BigDecimal priceWithTax(BigDecimal net, BigDecimal ratePercent) {
        return net.multiply(BigDecimal.ONE.add(ratePercent.movePointLeft(2)))
                .setScale(2, RoundingMode.HALF_UP);
    }

    public static void main(String[] args) throws Exception {
        try (Connection c = DriverManager.getConnection("jdbc:h2:mem:esc", "sa", "");
             Statement st = c.createStatement()) {
            st.execute("CREATE TABLE product (name VARCHAR(20), price DECIMAL(8,2))");
            st.execute("INSERT INTO product VALUES ('pen', 1.50), ('lamp', 19.99)");
            st.execute("CREATE ALIAS PRICE_WITH_TAX FOR 'EscapeSyntax.priceWithTax'");

            // nativeSQL shows what the driver sends for JDBC escape syntax
            String[] escapes = {
                "{call PRICE_WITH_TAX(?, ?)}",
                "{? = call PRICE_WITH_TAX(?, ?)}",
                "SELECT {fn UCASE(name)} FROM product",
                "SELECT * FROM product WHERE added > {d '2026-01-15'}",
            };
            for (String sql : escapes) {
                System.out.printf("%-55s -> %s%n", sql, c.nativeSQL(sql).strip());
            }

            // Escapes work in ordinary statements too
            try (ResultSet rs = st.executeQuery(
                    "SELECT {fn UCASE('abc')}, {fn LENGTH('hello')}, {d '2026-01-15'}")) {
                rs.next();
                System.out.println("{fn UCASE}, {fn LENGTH}, {d}: " + rs.getString(1) + ", "
                        + rs.getInt(2) + ", " + rs.getObject(3).getClass().getSimpleName() + " "
                        + rs.getObject(3));
            }

            // A function can also be used directly inside a query, once per row
            try (PreparedStatement ps = c.prepareStatement(
                    "SELECT name, price, PRICE_WITH_TAX(price, ?) FROM product ORDER BY name")) {
                ps.setBigDecimal(1, new BigDecimal("25"));
                try (ResultSet rs = ps.executeQuery()) {
                    while (rs.next()) {
                        System.out.println("in SELECT: " + rs.getString(1) + " "
                                + rs.getBigDecimal(2) + " -> " + rs.getBigDecimal(3));
                    }
                }
            }
        }
    }
}

Output:

Output
{call PRICE_WITH_TAX(?, ?)}                             -> call PRICE_WITH_TAX(?, ?)
{? = call PRICE_WITH_TAX(?, ?)}                         -> ? = call PRICE_WITH_TAX(?, ?)
SELECT {fn UCASE(name)} FROM product                    -> SELECT     UCASE(name)  FROM product
SELECT * FROM product WHERE added > {d '2026-01-15'}    -> SELECT * FROM product WHERE added >  d '2026-01-15'
{fn UCASE}, {fn LENGTH}, {d}: ABC, 5, Date 2026-01-15
in SELECT: lamp 19.99 -> 24.99
in SELECT: pen 1.50 -> 1.88
  • H2's translation simply drops the braces, because its own syntax is CALL name(...). Other drivers do more work: for Oracle, {call p(?)} becomes a PL/SQL block. The escape lets the same Java code run on several databases.
  • {fn UCASE(...)} and {fn LENGTH(...)} are scalar function escapes; the JDBC specification lists a set of string, numeric, date and system functions that drivers should map. {d '2026-01-15'} is a date literal that every driver understands, and here it came back as a java.sql.Date. Other escapes are {t ...} and {ts ...} for times and timestamps, {oj ...} for outer joins and {escape '!'} for LIKE escapes.
  • A function can be called inside a normal SELECT, once per row: the lamp's 19.99 became 24.99 and the pen's 1.50 became 1.88. For functions without side effects this is often simpler than a CallableStatement, and it works with every result set feature.
  • Escapes are processed in every statement type by default. Statement.setEscapeProcessing(false) turns that off, which a few drivers need for SQL that contains literal braces.

Transactions, errors and parameter metadata

A procedure is not a separate world: it runs inside the caller's session. The program registers an ADD_ORDER procedure that inserts a row through the caller's connection, calls it twice in a transaction and rolls back, then passes an invalid quantity, and finally asks the metadata what it knows about the procedure.

Java
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;

public class ProcedureBehavior {

    // Writes a row using the caller's connection, and so the caller's transaction
    public static int addOrder(Connection conn, String item, int qty) throws SQLException {
        if (qty <= 0) {
            throw new IllegalArgumentException("quantity must be positive: " + qty);
        }
        try (var ps = conn.prepareStatement("INSERT INTO orders (item, qty) VALUES (?, ?)")) {
            ps.setString(1, item);
            ps.setInt(2, qty);
            return ps.executeUpdate();
        }
    }

    static int orders(Connection c) throws SQLException {
        try (Statement st = c.createStatement();
             ResultSet rs = st.executeQuery("SELECT COUNT(*) FROM orders")) {
            rs.next();
            return rs.getInt(1);
        }
    }

    static void call(Connection c, String item, int qty) throws SQLException {
        try (CallableStatement cs = c.prepareCall("{? = call ADD_ORDER(?, ?)}")) {
            cs.registerOutParameter(1, Types.INTEGER);
            cs.setString(2, item);
            cs.setInt(3, qty);
            cs.execute();
            System.out.println("ADD_ORDER(" + item + ", " + qty + ") returned " + cs.getInt(1));
        }
    }

    public static void main(String[] args) throws Exception {
        try (Connection c = DriverManager.getConnection("jdbc:h2:mem:pb", "sa", "");
             Statement st = c.createStatement()) {
            st.execute("CREATE TABLE orders (item VARCHAR(20), qty INT)");
            st.execute("CREATE ALIAS ADD_ORDER FOR 'ProcedureBehavior.addOrder'");

            // 1. The procedure's work is part of the caller's transaction
            c.setAutoCommit(false);
            call(c, "pen", 2);
            call(c, "pad", 1);
            System.out.println("orders before rollback: " + orders(c));
            c.rollback();
            System.out.println("orders after rollback:  " + orders(c));

            // 2. An exception inside the procedure arrives as an SQLException
            try {
                call(c, "ink", 0);
            } catch (SQLException e) {
                System.out.println("failure: SQLState " + e.getSQLState() + ", cause "
                        + e.getCause());
            }

            // 3. What the metadata says about procedures and their parameters
            DatabaseMetaData md = c.getMetaData();
            System.out.println("supportsStoredProcedures: " + md.supportsStoredProcedures()
                    + ", supportsNamedParameters: " + md.supportsNamedParameters());
            try (ResultSet rs = md.getProcedureColumns(null, "PUBLIC", "ADD_ORDER", "%")) {
                while (rs.next()) {
                    int type = rs.getInt("COLUMN_TYPE");
                    String mode = switch (type) {
                        case DatabaseMetaData.procedureColumnIn -> "IN";
                        case DatabaseMetaData.procedureColumnReturn -> "RETURN";
                        case DatabaseMetaData.procedureColumnOut -> "OUT";
                        default -> "type " + type;
                    };
                    System.out.println("  parameter " + rs.getString("COLUMN_NAME") + ": "
                            + rs.getString("TYPE_NAME") + " " + mode);
                }
            }
        }
    }
}

Output:

Output
ADD_ORDER(pen, 2) returned 1
ADD_ORDER(pad, 1) returned 1
orders before rollback: 2
orders after rollback:  0
failure: SQLState 90105, cause java.lang.IllegalArgumentException: quantity must be positive: 0
supportsStoredProcedures: false, supportsNamedParameters: false
  parameter RESULT: INTEGER RETURN
  parameter P1: CHARACTER VARYING IN
  parameter P2: INTEGER IN
  • Both calls returned 1 and the table held 2 orders, but after rollback() it held 0. The procedure's insert belonged to the caller's transaction. This is the normal behavior on other databases as well, unless the procedure commits itself or uses an autonomous transaction, as Oracle allows.
  • The IllegalArgumentException thrown inside the procedure arrived as an SQLException with H2's state 90105 ("exception calling user-defined function") and the original exception as its cause. On other databases, a procedure signals errors with RAISE, RAISERROR or SIGNAL, and you choose the SQLState, so agree on codes the Java side can check.
  • H2 reports supportsStoredProcedures() as false, even though the calls above worked, because its aliases are not procedures in the SQL standard's sense. Treat these capability flags as hints and test the feature itself.
  • getProcedureColumns listed the return value and two IN parameters, named P1 and P2 by H2. Named parameters are not supported here, so calls must use positions. Drivers for Oracle and SQL Server report real parameter names and support setInt("qty", ...).

OUT parameters and result sets on other databases

H2 cannot demonstrate OUT parameters, and the main databases differ in how procedures hand data back. The table summarizes the vendors' documented approaches; it was not run on this page, so test calls against the database you use.

How procedures return data on common databases
DatabaseTypical approach in JDBC
OracleOUT parameters via registerOutParameter; result sets as REF CURSOR OUT parameters
SQL ServerOUT parameters, a return status, and one or more result sets read with getMoreResults()
MySQLOUT and IN OUT parameters, and result sets from SELECT statements in the procedure
PostgreSQLFunctions that return values or tables, called with {? = call ...} or SELECT * FROM fn(?); procedures (since PostgreSQL 11) with CALL
H2Java methods registered with CREATE ALIAS: one return value or one result set

With OUT parameters, the order is always the same: set the IN values, call registerOutParameter for every OUT and IN OUT position with its SQL type, run execute(), and only then read the OUT values with the getters. When a procedure returns result sets as well as OUT parameters, read all the result sets first; some drivers only make the OUT values available after that.

ResultSetMetaData: describing any query

A program that runs queries it does not know in advance, such as a report generator or a SQL console, can ask the result set for its columns. This matters for procedures in particular, because the shape of the rows a procedure returns is not visible in the Java code. The printer below never mentions a column name, yet prints the table and a description of every column, including a computed one.

Java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;

// Prints any query as a table using only ResultSetMetaData: no knowledge of the columns needed
public class ResultSetPrinter {

    static void print(ResultSet rs) throws Exception {
        ResultSetMetaData md = rs.getMetaData();
        int n = md.getColumnCount();
        StringBuilder header = new StringBuilder();
        for (int i = 1; i <= n; i++) {
            header.append(String.format("%-12s", md.getColumnLabel(i)));
        }
        System.out.println(header.toString().stripTrailing());
        while (rs.next()) {
            StringBuilder row = new StringBuilder();
            for (int i = 1; i <= n; i++) {
                Object v = rs.getObject(i);
                row.append(String.format("%-12s", v));
            }
            System.out.println(row.toString().stripTrailing());
        }
        for (int i = 1; i <= n; i++) {
            String nullable = switch (md.isNullable(i)) {
                case ResultSetMetaData.columnNoNulls -> "NOT NULL";
                case ResultSetMetaData.columnNullable -> "nullable";
                default -> "unknown";
            };
            System.out.printf("  %-8s SQL %-17s Java %-20s %s%n", md.getColumnLabel(i),
                    md.getColumnTypeName(i), md.getColumnClassName(i), nullable);
        }
    }

    public static void main(String[] args) throws Exception {
        try (Connection c = DriverManager.getConnection("jdbc:h2:mem:meta", "sa", "");
             Statement st = c.createStatement()) {
            st.execute("CREATE TABLE product (name VARCHAR(20) NOT NULL, stock INT, "
                    + "price DECIMAL(8,2))");
            st.execute("INSERT INTO product VALUES ('pen', 120, 1.50), ('pad', 8, NULL)");
            try (ResultSet rs = st.executeQuery(
                    "SELECT name, stock, price, stock * 2 AS doubled FROM product")) {
                print(rs);
            }
        }
    }
}

Output:

Output
NAME        STOCK       PRICE       DOUBLED
pen         120         1.50        240
pad         8           null        16
  NAME     SQL CHARACTER VARYING Java java.lang.String     NOT NULL
  STOCK    SQL INTEGER           Java java.lang.Integer    nullable
  PRICE    SQL DECIMAL           Java java.math.BigDecimal nullable
  DOUBLED  SQL INTEGER           Java java.lang.Integer    unknown
  • getColumnLabel returns the AS alias where there is one, so the computed column is called DOUBLED. getColumnName would return the underlying name instead.
  • getColumnClassName tells you what getObject will return: DECIMAL becomes BigDecimal, and the NULL price comes back as Java null.
  • Nullability is known for table columns, matching the NOT NULL in the table definition, but reported as unknown for the computed expression.

Procedure, query or application code?

Where to put database logic
SituationUse
Logic that needs many rows but returns little, over a slow networkA stored procedure or a single set-based SQL statement
Users may run an operation but not touch its tablesA procedure with EXECUTE permission only
A calculation used in queriesA function called inside SELECT
Business rules that change often or need unit testsApplication code with PreparedStatement
Code that must run on several databasesApplication code, or the {call} escape with procedures kept simple
Inspecting procedures or unknown result setsDatabaseMetaData and ResultSetMetaData

For transactions around procedure calls, see transactions and batches; for connections and types, see JDBC basics.