Retrieving data from tables using the PreparedStatement.executeQuery method
To retrieve data from a table using a SELECT statement with parameter markers, you use the PreparedStatement.executeQuery method.
About this task
This method returns a result table in a ResultSet object. After you obtain the result table, you need to use ResultSet methods to move through the result table and obtain the individual column values from each row.
With the IBM® Data Server Driver for JDBC and SQLJ, you can also use the PreparedStatement.executeQuery method to retrieve a result set from a stored procedure call, if that stored procedure returns only one result set and has only input parameters. If the stored procedure returns multiple result sets, you need to use the PreparedStatement.execute method.
You can also use the PreparedStatement.executeQuery method for statements that have no parameter markers. When you execute a query many times, you can get better performance by creating the SQL statement as a PreparedStatement.
Procedure
To retrieve rows from a table using a SELECT statement with parameter markers, you need to perform these steps:
Example
String empnum, phonenum;
Connection con;
PreparedStatement pstmt;
ResultSet rs;
…
pstmt = con.prepareStatement(
"SELECT EMPNO, PHONENO FROM EMPLOYEE WHERE EMPNO=?");
// Create a PreparedStatement object 1
pstmt.setString(1,"000010"); // Assign value to input parameter 2
rs = pstmt.executeQuery(); // Get the result table from the query 3
while (rs.next()) { // Position the cursor 4
empnum = rs.getString(1); // Retrieve the first column value
phonenum = rs.getString(2); // Retrieve the first column value
System.out.println("Employee number = " + empnum +
"Phone number = " + phonenum);
// Print the column values
}
rs.close(); // Close the ResultSet 5
pstmt.close(); // Close the PreparedStatement 6