Nearby lessons
19 of 37JDBC - Stored Procedures and CallableStatement
- What a stored procedure is and why we use it
- Each variation in its own program: IN params, IN+OUT params, ResultSet-returning procedure
- Calling procedures from Java with CallableStatement
- Batch updates — Statement version and PreparedStatement version
Stored Procedures and CallableStatement is a fundamental part of database programming with JDBC. This lesson explains What is a Stored Procedure?, Creating a Stored Procedure (MySQL) and Program 1: Calling a Procedure with IN and OUT Parameters with complete, runnable code examples, clear step-by-step explanations, and common mistakes to avoid with exam-style MCQs at the end.
What is a Stored Procedure?
A stored procedure is a block of SQL statements stored inside the database itself with a name. Instead of sending many SQL statements from Java, you send one call to the procedure, and the database runs all the statements inside it.
Why use stored procedures?
- Performance — the procedure is already compiled in the database.
- Less network traffic — one call instead of many queries.
- Reusability — many applications can call the same procedure.
- Security — the database can hide the table details.
Creating a Stored Procedure (MySQL)
The three parameter types you will meet:
| Parameter type | Meaning |
|---|---|
| IN | Value passed INTO the procedure (like a method parameter) |
| OUT | Value returned FROM the procedure (like a return value) |
| INOUT | Both — a value goes in and a new value comes out |
Program 1: Calling a Procedure with IN and OUT Parameters
CallableStatement is the JDBC interface (child of PreparedStatement) used to call stored procedures. Here addProc(IN x, IN y, OUT z) adds two numbers and returns the sum.
Program 2: Procedure that Returns a ResultSet
Some procedures run a SELECT and return rows. In MySQL, use executeQuery() and read the ResultSet like normal.
Program 3: Procedure with a Salary OUT Parameter
A more realistic example: a procedure that looks up an employee and returns a value (OUT) back to Java.
- Stored procedure = SQL statements stored in the database, called by name.
- Separate programs: IN+OUT params, ResultSet-returning procedure, OUT salary.
- CallableStatement (child of PreparedStatement) calls procedures.
- IN parameters set with setXxx; OUT parameters registered with registerOutParameter and read with getXxx.
- Batch updates: Statement (different queries) and PreparedStatement (same query, many values).
- addBatch + executeBatch run many statements in one round-trip.