Question: What will the following code fragment print when compiled and run?
Connection c = DriverManager.getConnection("jdbc:derby://localhost:1527/sample", "app", "app");
try(Statement stmt = c.createStatement();){
ResultSet rs = stmt.executeQuery("select * from STUDENT");
while(rs.next()){
System.out.println(rs.getString(1));
}
}
catch(SQLException e){
System.out.println("Exception ");
}
(Assume that items not specified such as import statements and try/catch block are all valid.)
- It will throw an exception if the first column of the result is not a String.
- It will throw an exception every time it is run irrespective of what the query returns.
- It will print the value for the first column of the result and if there is no row in STUDENT table, it will not print anything.
- It will not compile.
Answer: c
Explanation:
a. Since Object class has a
toString()
method, any type can be converted to a String.
So this cannot be a cause of the exception. If you use
getInt()
or getDouble and if the column value cannot be converted to an int or double,
then that will cause an Exception.