Nearby lessons
20 of 37JDBC - Cursors and Stored Functions
- What cursors are and the two types
- SYS_REFCURSOR — returning a ResultSet from a procedure
- Stored functions vs stored procedures
- Working with Excel files (modern approach)
Cursors and Stored Functions is a fundamental part of database programming with JDBC. This lesson explains What is a Cursor?, SYS_REFCURSOR — Procedure Returning a ResultSet and Stored Functions vs Stored Procedures 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 Cursor?
A cursor is a database object used to access the results of a SQL query row by row. When a SELECT runs, the database stores the result in an area — a cursor lets you walk through those rows one at a time.
There are two types of cursors:
| Type | Who creates it | Example |
|---|---|---|
| Implicit cursor | The database automatically, for every SQL statement | %ROWCOUNT, %FOUND (Oracle) |
| Explicit cursor | The developer, for a particular query | SYS_REFCURSOR (Oracle) |
Two useful Oracle implicit-cursor attributes:
| Attribute | What it tells |
|---|---|
| %ROWCOUNT | How many rows were affected by the last SQL statement |
| %FOUND | Whether any row was affected (true/false) |
SYS_REFCURSOR — Procedure Returning a ResultSet
A normal OUT parameter returns a single value. To return a whole result set from a procedure, Oracle uses the SYS_REFCURSOR type. From JDBC we register it with OracleTypes.CURSOR and read it as a ResultSet.
SYS_REFCURSOR — Procedure Returning a ResultSet
Stored Functions vs Stored Procedures
A function is like a procedure but it returns a value and is used inside SQL expressions.
| Point | Stored procedure | Stored function |
|---|---|---|
| Returns | Zero or more values (OUT params), or nothing | Exactly one value |
| Called from | Java (CallableStatement) | Java or inside SQL (SELECT fun() ...) |
| Keyword | CREATE PROCEDURE | CREATE FUNCTION |
| Used for | Actions (insert, transfer, report) | Computing a value (salary bonus, tax) |
Stored Functions vs Stored Procedures
- Cursor = database object to walk through SQL results row by row.
- Implicit cursors are auto-created (%ROWCOUNT, %FOUND); explicit ones are created by the developer (SYS_REFCURSOR).
- SYS_REFCURSOR lets a procedure return a whole ResultSet; register it with OracleTypes.CURSOR.
- Function returns one value and can be used inside SQL; procedure performs actions.
- The old Excel-via-ODBC approach is gone; use Apache POI to read/write Excel today.