Oracle Certified Professional Java Se 8 Programmer · Free Practice Question Hard
Question 47
Given structure of MESSAGES table:
MESSAGES (msg1 varchar(100), msg2 varchar(100))
MESSAGES table contains below records: 'Happy New Year!', 'Happy Holidays!'
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 = "DELETE FROM MESSAGES";
- try (Connection con = DriverManager.getConnection(url, user, password);
- Statement stmt = con.createStatement();
- ResultSet rs = stmt.executeQuery(query);)
- {
- rs.next();
- 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.
What will be the result of compiling and executing Test class?
- A An exception is thrown at runtime
- B Compilation error
- C 1
- D 0
Reveal correct answer
Correct answer: A
Explanation
stmt.executeQurey(String) method can accept any String and it returns ResultSet instance, hence no compilation error.
But stmt.executeQuery(String) method cannot issue INSERT, UPDATE and DELETE statements. Hence, 'stmt.executeQuery(query)' throws SQLException at runtime.
To issue INSERT, UPDATE or DELETE statements either use stmt.execute(String) method OR stmt.executeUpdate(String) method.
- try (Connection con = DriverManager.getConnection(url, user, password);
- Statement stmt = con.createStatement();)
- {
- boolean res = stmt.execute(query);
- System.out.println(stmt.getUpdateCount());
- }
OR
- try (Connection con = DriverManager.getConnection(url, user, password);
- Statement stmt = con.createStatement();)
- {
- System.out.println(stmt.executeUpdate(query));
- }
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
