Oracle Certified Professional Java Se 8 Programmer · Free Practice Question Medium
Question 1
Given structure of LOG table:
LOG (ID integer, MESSAGE varchar(1000), PRIMARY KEY (ID))
Given code of Test.java file:
- package com.udayan.ocp;
- import java.sql.*;
- import java.util.Properties;
- public class Test {
- public static void main(String[] args) throws Exception {
- String url = "jdbc:mysql://localhost:3306/ocp";
- Properties prop = new Properties();
- prop.put("user", "root");
- prop.put("password", "password");
- String query = "Select count(*) FROM LOG";
- try (Connection con = DriverManager.getConnection(url, prop);
- Statement stmt = con.createStatement();
- ResultSet rs = stmt.executeQuery(query);)
- {
- System.out.println(rs.getInt(1));
- }
- }
- }
Also assume:
URL is correct and db credentials are: root/password.
SQL query is correct and valid.
The JDBC 4.2 driver jar is configured in the classpath.
LOG table doesn't have any records.
What will be the result of compiling and executing Test class?
- A 1
- B 0
-
C
An exception is thrown at runtime
Reveal correct answer
Correct answer: C
Explanation
As credentials are passed as java.util.Properties so user name should be passed as "user" property and password should be passed as "password" property.
In the given code, correct property names 'user' and 'password' are used. As URL and DB credentials are correct, hence no issues in connecting the database.
Given query returns just one column containing no. of records, 0 in this case.
But ResultSet cursor is initially before the first record, hence 'rs.getInt(1)' throws SQLException at runtime.
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
