Oracle Certified Professional Java Se 11 Developer · Free Practice Question Medium
Question 37
Question ID: UKOCP86082
Given structure of EMPLOYEE table:
EMPLOYEE (ID integer, FIRSTNAME varchar(100), LASTNAME varchar(100), SALARY real, PRIMARY KEY (ID))
Given code of Test.java file:
- package com.udayankhattry.ocp;
- import java.sql.*;
- public class Test {
- public static void main(String[] args) throws Exception {
- var url = "jdbc:mysql://localhost:3306/ocp";
- var user = "root";
- var password = "password";
- var query = "INSERT INTO EMPLOYEE VALUES(?, ?, ?, ?)";
- try (var con = DriverManager.getConnection(url, user, password);
- var ps = con.prepareStatement(query);
- ) {
- ps.setInt(1, 101);
- ps.setObject(3, "Smith");
- ps.setString(2, "John");
- ps.setDouble(4, 12000.0);
- ps.executeUpdate();
- }
- }
- }
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.
EMPLOYEE table doesn't have any records.
What is the result?
- A The program executes successfully and one record is inserted in the EMPLOYEE table
- B The program executes successfully but no record is inserted in the EMPLOYEE table
- C An exception is thrown at runtime
- D Compilation error
Reveal correct answer
Correct answer: A
Explanation
UKOCP86082:
Variables 'url', 'user', 'password' and 'query' infer to String type. Variable 'con' infers to Connection type and variable 'ps' infers to PreparedStatement type.
Column index starts with 1 and not 0, hence in the query string, 1st ? represents the place holder for the value of 1st column and so on.
ps.setInt(1, 101); => Sets 101 for ID column (1st ? mark).
ps.setObject(3, "Smith"); => Sets Smith for LASTNAME column (3rd ? mark).
ps.setString(2, "John"); => Sets John for FIRSTNAME column (2nd ? mark).
ps.setDouble(4, 12000.0); => Sets 12000.0 for SALARY column (4th ? mark).
ps.executeUpdate(); inserts one row (101, "John", "Smith", 12000.0) in the database.
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
