JDBC Online Test - MCQ Questions

Welcome to JDBC Online Test!. We will present 45 MCQs (Multiple-Choice Questions) on JDBC to test your knowledge of using JDBC in Java applications.

You can select the correct answer for each question and submit the test. You will get your online test score after finishing the complete test.

1. What does JDBC stand for?

a) Java Database Connectivity
b) Java Data Connection
c) Java Development Connection
d) Java Database Connection

2. Which interface is not part of JDBC?

a) Connection
b) Statement
c) ResultSet
d) DatabaseManager

3. What does the following JDBC code snippet do?

Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/test", "user", "password");
a) Connects to a MySQL database located at localhost with the database name 'test'
b) Creates a new MySQL database called 'test'
c) Connects to an Oracle database with the default settings
d) Deletes a MySQL database named 'test'

4. How do you load a database driver in JDBC?

a) Class.forName("com.mysql.jdbc.Driver");
b) DriverManager.loadDriver("com.mysql.jdbc.Driver");
c) DriverManager.getConnection("com.mysql.jdbc.Driver");
d) LoadDriver("com.mysql.jdbc.Driver");

5. Which method is used to execute a SQL query in JDBC?

a) executeQuery()
b) executeSQL()
c) queryExecute()
d) runQuery()

6. Which interface is primarily used to execute SQL statements with JDBC?

a) DriverManager
b) Connection
c) Statement
d) ResultSet

7. How do you handle SQL exceptions in JDBC?

a) Using a try-catch block
b) Using a throw statement
c) Using a finally block
d) SQL exceptions cannot be handled

8. What does the following code return, assuming all connections and SQL syntax are correct?

PreparedStatement pstmt = conn.prepareStatement("UPDATE Users SET age=? WHERE id=?");
pstmt.setInt(1, 30);
pstmt.setInt(2, 1);
int updated = pstmt.executeUpdate();
a) The number of rows updated
b) True if the update was successful
c) False if the update failed
d) None of the above

9. How do you start a transaction in JDBC?

a) conn.setAutoCommit(true);
b) conn.setAutoCommit(false);
c) conn.commit();
d) conn.startTransaction();

10. What is the purpose of the ResultSetMetaData interface?

a) To get information about the types and properties of the columns in a ResultSet
b) To update data in a ResultSet
c) To move the cursor in a ResultSet
d) To execute SQL queries

11. How can you retrieve the value of a column named "email" from a ResultSet?

a) rs.getString("email");
b) rs.getEmail("email");
c) rs.valueOf("email");
d) rs.query("email");

12. What does the commit() method do in JDBC?

a) Saves changes made during a transaction to the database
b) Rolls back changes made during the transaction
c) Starts a new transaction
d) Ends the current session

13. Which method is used to roll back changes made during the current transaction?

a) conn.rollback();
b) conn.commit();
c) conn.undo();
d) conn.restore();

14. What does setAutoCommit(false) do in a JDBC connection?

a) Disables automatic execution of the commit statement
b) Forces each SQL statement to be committed immediately
c) Enables batch updates
d) None of the above

15. How do you move the cursor to the last row of a ResultSet?

a) rs.final();
b) rs.end();
c) rs.last();
d) rs.finish();

16. What is the enhanced for-loop syntax for traversing a ResultSet in JDBC 4?

a) Not supported in JDBC 4
b) for(ResultSet rs : stmt.executeQuery(query)) {}
c) while(rs.next()) {}
d) rs.forEach(row -> {});

17. What is the function of the DatabaseMetaData interface?

a) To provide methods to retrieve data from the database
b) To modify database schemas
c) To get information about the database and the JDBC driver
d) To handle SQL exceptions

18. How do you retrieve a connection from a DataSource in JDBC?

a) DataSource.getConnection();
b) DriverManager.getConnection();
c) Connection.connect();
d) DataSource.connect();

19. What is the result of calling execute() on a Statement object?

a) Always returns a boolean
b) Always returns an int
c) Always returns a ResultSet
d) Returns a boolean or throws an SQLException

20. What does the following JDBC code snippet do?

Connection conn = DriverManager.getConnection(url, username, password);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM users");
a) Connects to the database and retrieves all records from the 'users' table
b) Updates records in the 'users' table
c) Deletes records from the 'users' table
d) Inserts records into the 'users' table

21. Which method is used to prepare a statement with JDBC that helps prevent SQL injection?

a) createStatement()
b) prepareStatement()
c) executeQuery()
d) executeUpdate()

22. What is the primary function of the 'executeUpdate' method in JDBC?

a) To execute SELECT queries
b) To execute DML statements like INSERT, UPDATE, or DELETE
c) To retrieve data from a database
d) To check the validity of a connection

23. Which of the following is true about the DriverManager class in JDBC?

a) It is used to establish a connection with the database.
b) It is used to execute SQL queries.
c) It is used to hold the result of a query.
d) It is used to update database records.

24. What JDBC component represents a session between a Java application and a database?

a) ResultSet
b) Statement
c) Connection
d) DriverManager

25. What will happen if you close a Connection object in JDBC?

a) The ResultSet objects created from it will still be valid.
b) The Statement objects created from it will still be valid.
c) It will close the connection to the database, invalidating any associated Statement and ResultSet objects.
d) None of the above.

26. What does the following JDBC code achieve?

Connection conn = DriverManager.getConnection(url, username, password);
conn.setAutoCommit(false);
PreparedStatement pstmt = conn.prepareStatement("INSERT INTO Users VALUES (?, ?)");
pstmt.setInt(1, 1);
pstmt.setString(2, "John Doe");
pstmt.executeUpdate();
conn.commit();
a) Inserts a single record into the Users table and commits the transaction
b) Inserts a single record into the Users table without committing the transaction
c) Updates a record in the Users table and commits the transaction
d) Deletes a record in the Users table and commits the transaction

27. How do you retrieve the auto-generated key after an insert operation in JDBC?

PreparedStatement pstmt = conn.prepareStatement("INSERT INTO Users(name) VALUES(?)", Statement.RETURN_GENERATED_KEYS);
pstmt.setString(1, "Jane Doe");
pstmt.executeUpdate();
ResultSet rs = pstmt.getGeneratedKeys();
if (rs.next()) {
    System.out.println("Generated key: " + rs.getInt(1));
}
a) Using ResultSet.getGeneratedKeys()
b) Using PreparedStatement.getGeneratedKeys()
c) Using Connection.getGeneratedKeys()
d) Using Statement.getGeneratedKeys()

28. What JDBC feature should be used to improve performance when inserting multiple records?

a) executeUpdate()
b) executeBatch()
c) executeQuery()
d) executeLargeUpdate()

29. What is the output of the following JDBC code when executed if there are no records in the 'users' table?

Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet rs = stmt.executeQuery("SELECT id FROM users");
rs.last();
System.out.println(rs.getRow());
a) 0
b) 1
c) The last row number in the ResultSet
d) Throws an SQLException

30. How can you move the cursor to the previous row in a ResultSet in JDBC?

ResultSet rs = stmt.executeQuery("SELECT id FROM users");
rs.next(); // Move to first row
rs.next(); // Move to second row
rs.previous(); // Move back to first row
System.out.println(rs.getInt("id"));
a) rs.previous()
b) rs.back()
c) rs.next()
d) rs.rewind()

31. What does setting the fetch size in a JDBC Statement do?

Statement stmt = conn.createStatement();
stmt.setFetchSize(100);
ResultSet rs = stmt.executeQuery("SELECT * FROM large_table");
a) Limits the number of rows returned by the query to 100
b) Suggests to the driver to fetch 100 rows at a time from the database cursor
c) Sets the maximum number of rows that can be inserted using this statement
d) Checks 100 rows at a time for any SQL exceptions

32. Which method is used to update data in an updatable ResultSet?

ResultSet rs = stmt.executeQuery("SELECT * FROM users WHERE id = 1");
if (rs.next()) {
    rs.updateString("name", "Updated Name");
    rs.updateRow();
}
a) rs.updateRow()
b) rs.refreshRow()
c) rs.commit()
d) rs.executeUpdate()

33. What is the correct way to handle transactions involving multiple update operations in JDBC?

conn.setAutoCommit(false);
try {
    Statement stmt = conn.createStatement();
    stmt.executeUpdate("UPDATE accounts SET balance = balance - 100 WHERE id = 1");
    stmt.executeUpdate("UPDATE accounts SET balance = balance + 100 WHERE id = 2");
    conn.commit();
    } catch (SQLException e) {
        conn.rollback();
    }
a) Set auto-commit to false, execute updates, and manually commit or rollback
b) Leave auto-commit as true, execute updates, and let JDBC handle transactions
c) Execute updates and call commit() after each update
d) Execute updates without handling transactions

34. How do you ensure that a JDBC resource is properly closed after use?

a) Manually close each resource at the end of the try block
b) Close each resource in the finally block to ensure they are closed even if an exception occurs
c) Resources do not need to be closed in modern Java applications
d) Let the garbage collector handle the closing of resources

35. What feature in JDBC 4 makes it unnecessary to explicitly load JDBC drivers using Class.forName()?

a) Automatic driver registration
b) Driver deregistration
c) JDBC API enhancements
d) SQL exception handling

36. How do you check if a connection to the database is still valid in JDBC 4?

Connection conn = DriverManager.getConnection(url, user, password);
boolean isValid = conn.isValid(10);
a) conn.isValid(10);
b) conn.isClosed();
c) conn.checkValid();
d) conn.isAlive(10);

37. What method is used to retrieve a list of all the available schemas in a database using JDBC 4?

Connection conn = DriverManager.getConnection(url, user, password);
ResultSet rs = conn.getMetaData().getSchemas();
a) conn.getMetaData().getSchemas();
b) conn.getSchemas();
c) conn.getSchemaList();
d) conn.getMetaData().getAllSchemas();

38. Which feature in JDBC 4 simplifies error handling?

a) SQLWarning enhancements
b) SQLException subclassing
c) New methods in SQLException class
d) Automatic rollback on SQLException

39. What does the following code snippet demonstrate?

try (Connection conn = DriverManager.getConnection(url, user, password);
Statement stmt = conn.createStatement()) {
    ResultSet rs = stmt.executeQuery("SELECT * FROM Employees");
    while (rs.next()) {
        System.out.println(rs.getString("name"));
    }
}
a) SQL Injection
b) JDBC Connection pooling
c) Try-with-resources statement for automatic resource management
d) JDBC batching

40. How do you retrieve AUTO_INCREMENT field values assigned to a newly inserted row in JDBC 4?

PreparedStatement pstmt = conn.prepareStatement("INSERT INTO Employees(name) VALUES(?)",
Statement.RETURN_GENERATED_KEYS);
pstmt.setString(1, "John");
pstmt.executeUpdate();
ResultSet rs = pstmt.getGeneratedKeys();
if (rs.next()) {
    System.out.println("Generated key: " + rs.getInt(1));
}
a) pstmt.getGeneratedKeys();
b) conn.getGeneratedKeys();
c) stmt.getAutoIncrementValue();
d) rs.getAutoIncrementKeys();

41. What method is used to determine the major version of the JDBC API that is supported by the driver?

a) conn.getJDBCMajorVersion();
b) conn.getMetaData().getJDBCMajorVersion();
c) conn.getMetaData().getDriverVersion();
d) conn.getDriverInfo().getVersion();

42. What is the role of the RowId interface in JDBC 4?

a) It represents an SQL ROWID data type.
b) It is used to update the database schema.
c) It provides methods to commit transactions.
d) It is used to generate unique row identifiers in a table.

43. How can you improve the performance of bulk insert operations in JDBC 4?

PreparedStatement pstmt = conn.prepareStatement("INSERT INTO Employees(name) VALUES(?)");
for (String name : employeeNames) {
    pstmt.setString(1, name);
    pstmt.addBatch();
}
pstmt.executeBatch();
a) Using a PreparedStatement
b) Using addBatch() and executeBatch() methods
c) Using a CallableStatement
d) Increasing the buffer size

44. How do you retrieve column metadata from a ResultSet in JDBC 4?

ResultSet rs = stmt.executeQuery("SELECT * FROM Employees");
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
a) rs.getMetaData();
b) rs.getColumnData();
c) rs.getColumns();
d) rs.getResultSetMetaData();

45. What JDBC component handles SQL stored procedures?

a) PreparedStatement
b) CallableStatement
c) Statement
d) Connection

Comments