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.
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 CallableStatementPreparedStatement
| Method or syntax | Since | Purpose |
|---|---|---|
conn.prepareCall("{call p(?, ?)}") | JDBC 1 | Call a procedure |
"{? = call f(?)}" | JDBC 1 | Call a function; the first ? |
registerOutParameter(index, Types.X) | JDBC 1 | Declare an OUT or IN OUT parameter, or the return value |
getBigDecimal(index) | JDBC 1 | Read OUT values after execute() |
setInt("name", ...)getInt("name") | JDBC 3.0 | Named parameters, where the driver supports them |
getObject(index, Class) | JDBC 4.1 | Typed OUT values, including java.time |
executeQuery()getMoreResults() | JDBC 1 | Procedures 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
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.
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:
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
is the JDBC escape syntax for a function with a return value. The first{? = call NAME(?, ?)} is the return value, declared with? and read afterregisterOutParameter . 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.execute() calls a procedure. When it returns rows, read them with{call NAME(?)} like any query. Only the clip (3) and the pad (8) are below 10.executeQuery()- H2 passes the caller's
as the first Java argument ofConnection , so the procedure can run SQL. That argument does not appear in the SQL call.lowStock lists the procedures the database knows, which is useful for tools and for checking that a migration created them.DatabaseMetaData.getProcedures
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{fn ...}{d ...}
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:
{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
. Other drivers do more work: for Oracle,CALL name(...) becomes a PL/SQL block. The escape lets the same Java code run on several databases.{call p(?)} and{fn UCASE(...)} are scalar function escapes; the JDBC specification lists a set of string, numeric, date and system functions that drivers should map.{fn LENGTH(...)} is a date literal that every driver understands, and here it came back as a{d '2026-01-15'} . Other escapes arejava.sql.Date and{t ...} for times and timestamps,{ts ...} for outer joins and{oj ...} for LIKE escapes.{escape '!'}- A function can be called inside a normal
, 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 aSELECT , and it works with every result set feature.CallableStatement - Escapes are processed in every statement type by default.
turns that off, which a few drivers need for SQL that contains literal braces.Statement.setEscapeProcessing(false)
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
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:
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
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.rollback() - The
thrown inside the procedure arrived as anIllegalArgumentException with H2's stateSQLException ("exception calling user-defined function") and the original exception as its cause. On other databases, a procedure signals errors with90105 ,RAISE orRAISERROR , and you choose the SQLState, so agree on codes the Java side can check.SIGNAL - H2 reports
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.supportsStoredProcedures() listed the return value and two IN parameters, namedgetProcedureColumns andP1 by H2. Named parameters are not supported here, so calls must use positions. Drivers for Oracle and SQL Server report real parameter names and supportP2 .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.
| Database | Typical approach in JDBC |
|---|---|
| Oracle | OUTregisterOutParameterREF CURSOR |
| SQL Server | OUTgetMoreResults() |
| MySQL | OUTSELECT |
| PostgreSQL | Functions that return values or tables, called with {? = call ...}SELECT * FROM fn(?)CALL |
| H2 | Java methods registered with CREATE ALIAS |
With OUT parameters, the order is always the same: set the IN values, call registerOutParameterexecute()
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.
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:
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
returns thegetColumnLabel alias where there is one, so the computed column is calledAS .DOUBLED would return the underlying name instead.getColumnName tells you whatgetColumnClassName will return:getObject becomesDECIMAL , and theBigDecimal price comes back as JavaNULL .null- Nullability is known for table columns, matching the
in the table definition, but reported as unknown for the computed expression.NOT NULL
Procedure, query or application code?
| Situation | Use |
|---|---|
| Logic that needs many rows but returns little, over a slow network | A stored procedure or a single set-based SQL statement |
| Users may run an operation but not touch its tables | A procedure with EXECUTE |
| A calculation used in queries | A function called inside SELECT |
| Business rules that change often or need unit tests | Application code with |
| Code that must run on several databases | Application code, or the {call} |
| Inspecting procedures or unknown result sets | DatabaseMetaDataResultSetMetaData |
For transactions around procedure calls, see