What is the result of compiling and executing this code fragment?

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?

Given the code fragment:

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");
}

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



Leave a Reply 2

Your email address will not be published. Required fields are marked *


thiago

thiago

This question is incomplete or thre right anwser is wrong, need first move the cursor using ResultSet.netxt() method before using ResultSet.getInt(String)