Given the code fragment:
try {
String query = “SELECT * FROM Employee WHERE ID=110”;
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
System.out.println(“Employee ID: ” + rs.getInt(“ID”));
} catch (Exception se) {
System.out.println(“Error”);
}
Assume that the SQL query matches one record.
What is the result of compiling and executing this code?
A.
The code prints Error.
B.
The code prints the employee ID.
C.
Compilation fails due to an error at line 13.
D.
Compilation fails due to an error at line 14.
Explanation:
The code compiles fine.
The code will rune fine.public int getInt(String columnName)
throws SQLException
Retrieves the value of the designated column in the current row of this ResultSet object as an int in the Java programming language
there is no Connection found in the code, just “Statement stmt = conn.createStatement“. How the code will be compiled?
Given a code fragment…
Correct answer is A becoz we need to iterate the resultset to print the data eventhough single record. The above will result in Invalid cursor state exception
+1
It would throw SQLException.
+1
+1
A, the cursor is before the first record, so we need rs.next() before retrieving the record
+1
+1
+1
A
Strange. I just tried the following code (I’m using sqlite-jdbc-3.8.10.1):
String query = “SELECT file_path, file_name, creation_date FROM MUSIC_TRACK “;
Connection connection = DatabaseConnection.getInstance().getConnection();
try {
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery(query);
String filePath = rs.getString(1);
String fileName = rs.getString(2);
musicTrack = new MusicTrack(filePath, fileName);
System.out.println(musicTrack.getFilePath() + musicTrack.getFileName());
} catch (Exception ex) {
Logger.getLogger(Library.class.getName()).log(Level.SEVERE, null, ex);
}
And it works fine, output is:
C:/music/track1.mp3
So the answer should be B
If I change query to
SELECT file_path, file_name, creation_date FROM MUSIC_TRACK WHERE record_id = 3
which returns no records, I get java.sql.SQLException: ResultSet closed
A. The code prints Error.
Issue: “ResultSet not positioned properly, perhaps you need to call next.”
a
A, definitely. You can’t count on the ‘show answer’ button to be correct all the time!