Oracle Certified Professional Java Se 8 Programmer · Free Practice Question Hard
Question 2
Given structure of EMPLOYEE table:
EMPLOYEE (ID integer, FIRSTNAME varchar(100), LASTNAME varchar(100), SALARY real, PRIMARY KEY (ID))
EMPLOYEE table contains below records:
- 101 John Smith 12000
- 102 Sean Smith 15000
- 103 Regina Williams 15500
- 104 Natasha George 14600
Given code of Test.java file:
- package com.udayan.ocp;
- import java.sql.*;
- public class Test {
- public static void main(String[] args) throws SQLException {
- String url = "jdbc:mysql://localhost:3306/ocp";
- String user = "root";
- String password = "password";
- String query = "Select ID, FIRSTNAME, LASTNAME, SALARY FROM EMPLOYEE ORDER BY ID";
- try (Connection con = DriverManager.getConnection(url, user, password);
- Statement stmt = con.createStatement();
- ResultSet rs = stmt.executeQuery(query);) {
- rs.moveToInsertRow();
- rs.updateInt(1, 105);
- rs.updateString(2, "Smita");
- rs.updateString(3, "Jain");
- rs.updateDouble(4, 16000);
- rs.insertRow();
- }
- }
- }
Also assume:
URL, username and password are correct.
SQL query is correct and valid.
The JDBC 4.2 driver jar is configured in the classpath.
What will be the result of compiling and executing Test class?
-
A
Program executes successfully and a new record is inserted in the database
-
B
Program executes successfully but no new record is inserted in the database
-
C
An exception is thrown at runtime
Reveal correct answer
Correct answer: C
Explanation
By default ResultSet is not updatable.
'rs.moveToInsertRow();' throws an exception at runtime.
To update the ResultSet in any manner (insert, update or delete), the ResultSet must come from a Statement that was created with a ResultSet type of ResultSet.CONCUR_UPDATABLE.
NOTE: If you want to successfully insert a new record, then replace 'con.createStatement();' with
'con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);'
OR
'con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);'.
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
