Given the code fragment:
<code>
String query = “SELECT ID FROM Employee”; \\ Line 1
try (Statement stmt = conn.CreateStatement()) { \\ Line 2
ResultSet rs = stmt.executeQuery(query); \\ Line 3
stmt.executeQuery (“SELECT ID FROM Customer”); \\ Line 4
while (rs.next()) {
\\process the results
System.out.println (“Employee ID: ” + rs.getInt(“ID”) );
}
} catch (Exception e) {
system.out.println (“Error”);
}
</code>
Assume that the SQL queries return records. What is the result of compiling and executing this code fragment?
A.
The program prints employees IDs.
B.
The program prints customer IDs.
C.
The program prints Error.
D.
Compilation fails on line 13.
Explanation:
Line 3 sets the resultset rs. rs will contain IDs from the employee table.
Line 4 does not affect the resultset rs. It just returns a resultset (which is not used).Note:
A ResultSet object is a table of data representing a database result set, which is usually generated by executing a statement that queries the database.
You access the data in a ResultSet object through a cursor. Note that this cursor is not a database cursor. This cursor is a pointer that points to one row of data in the ResultSet. Initially, the cursor is positioned before the first row. The method ResultSet.next moves the cursor to the next row. This method returns false if the cursor is positioned after the last row. This method repeatedly calls the ResultSet.next method with a while loop to iterate through all the data in the ResultSet.
Reference: The Java Tutorials,Retrieving and Modifying Values from Result Sets
Corect answer is C. Error is: Operation not allowed after ResultSet closed.
Because after executing the second query, the first one is automatically closed.
This is also written in the official doc.
+1
+1
+1