10.3 ResultSet Explained
The ResultSet
interface in JDBC (Java Database Connectivity) represents the result set of a database query. It provides methods to navigate through the result set and retrieve data. Understanding ResultSet
is crucial for processing query results in Java SE 11 applications.
Key Concepts
1. ResultSet Interface
The ResultSet
interface is used to hold the data returned by a database query. It acts as a pointer to the data, allowing you to iterate through the rows and access the columns.
Example
Statement stmt = connection.createStatement(); ResultSet rs = stmt.executeQuery("SELECT * FROM employees");
2. Navigating ResultSet
The ResultSet
interface provides methods to move the cursor to different positions within the result set. Common methods include next()
, previous()
, first()
, last()
, and absolute()
.
Example
while (rs.next()) { int id = rs.getInt("id"); String name = rs.getString("name"); System.out.println("ID: " + id + ", Name: " + name); }
3. Retrieving Data
The ResultSet
interface provides methods to retrieve data from the current row. These methods include getInt()
, getString()
, getDouble()
, and others, which take the column name or index as an argument.
Example
int id = rs.getInt("id"); String name = rs.getString("name"); double salary = rs.getDouble("salary");
4. ResultSet Types
There are different types of ResultSet
objects that can be created using the Statement
interface. These types determine the behavior of the ResultSet
, such as whether it is scrollable, updatable, or sensitive to changes.
Example
Statement stmt = connection.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY ); ResultSet rs = stmt.executeQuery("SELECT * FROM employees");
5. ResultSet Metadata
The ResultSetMetaData
interface provides information about the structure of the ResultSet
, such as the number of columns, column names, and data types.
Example
ResultSetMetaData rsmd = rs.getMetaData(); int columnCount = rsmd.getColumnCount(); for (int i = 1; i <= columnCount; i++) { String columnName = rsmd.getColumnName(i); System.out.println("Column " + i + ": " + columnName); }
Examples and Analogies
Think of a ResultSet
as a table of data returned by a database query. The cursor is like a pointer that moves through the rows of the table. The next()
method is like moving the pointer to the next row, and the getInt()
and getString()
methods are like reading the values from the cells in that row.
For example, if you have a table of employees, the ResultSet
would be like a list of employee records. The cursor starts at the first record, and you can move through the list to read each employee's details.
By mastering the ResultSet
interface, you can efficiently process and manipulate query results in your Java SE 11 applications, ensuring accurate and reliable data handling.