Skip to Main Content
Java Cookbook
book

Java Cookbook

by Ian F. Darwin
June 2001
Intermediate to advanced content levelIntermediate to advanced
888 pages
21h 1m
English
O'Reilly Media, Inc.
Content preview from Java Cookbook

Using Stored Procedures with JDBC

Problem

You want to use a procedure stored in the database (a stored procedure).

Solution

Use a CallableStatement .

Discussion

A stored procedure is a series of SQL statements[49] stored as part of the database for use by any SQL user or programmer, including JDBC developers. Stored procedures are used for the same reasons as prepared statements: efficiency and convenience. Typically, the database administrator (DBA) at a large database shop will set up stored procedures and tell you what they are called, what parameters they require, and what they return. Putting the stored procedure itself into the database is totally database-dependent and not discussed here.

Suppose that I wish to see a list of user accounts that had not been used for a certain length of time. Instead of coding this logic into a JDBC program, I might define it using database-specific statements to write and store a procedure in the database, and then use the following code. Centralizing this logic in the database has some advantages for maintenance and also, in most databases, for speed.

CallableStatment cs = conn.prepareCall("{ call ListDefunctUsers }");
ResultSet rs = cs.executeQuery(  );

I then process the ResultSet in the normal way.

[49] And possibly some database-dependent utility statements.

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Practical Cloud-Native Java Development with MicroProfile

Practical Cloud-Native Java Development with MicroProfile

Emily Jiang, Andrew McCright, John Alcorn, David Chan, Alasdair Nottingham
Distributed Computing in Java 9

Distributed Computing in Java 9

Raja Malleswara Rao Malleswara Rao Pattamsetti

Publisher Resources

ISBN: 0596001703Supplemental ContentCatalog PageErrata