Question 1Easy
In PreparedStatement ps = con.prepareStatement("UPDATE t SET name = ? WHERE id = ?");, which call binds the id value 7?
- ps.setInt(1, 7)
- ps.setInt(2, 7)
- ps.setInt(0, 7)
- ps.setInt("id", 7)
Answer: B. ps.setInt(2, 7)
Explanation
Placeholders are numbered from 1 in the order they appear. The second ? is the id, so index 2.
Step-by-step solution
- First
? is index 1 (name). - Second
? is index 2 (id). - Call
setInt(2, 7).
Why the other options are wrong
- A. Index 1 is the name placeholder.
- C. JDBC parameter indexes start at 1, not 0.
- D. Named binding is not supported by PreparedStatement.
Question 3Medium
After ResultSet rs = stmt.executeQuery(sql);, what must you do before reading the first row's columns?
- Call rs.next()
- Call rs.previous()
- Nothing, the cursor is on row 1
- Call rs.getRow(0)
Answer: A. Call rs.next()
Explanation
A new ResultSet's cursor sits before the first row. next() moves it forward and returns false when no rows remain.
Step-by-step solution
- Cursor starts before row 1.
rs.next() advances to the first row.- Then call
rs.getString(...).
Why the other options are wrong
- B.
previous() moves backwards, away from the first row. - C. Reading before calling
next() throws an SQLException. - D.
getRow() returns the current row number; it does not move.
Question 4Hard
Which approach makes two SQL updates succeed or fail together in JDBC?
- Run two Statements one after another with the default settings
- Call executeBatch() on a Connection object after both updates
- Close the connection between the updates
- setAutoCommit(false), run both, then commit(), and rollback() on error
Answer: D. setAutoCommit(false), run both, then commit(), and rollback() on error
Explanation
Autocommit is on by default, so each statement commits immediately. Turn it off to group statements into one transaction.
Step-by-step solution
conn.setAutoCommit(false).- Execute both updates.
commit() on success, rollback() in the catch block.
Why the other options are wrong
- A. With autocommit each update commits alone.
- B.
executeBatch is a method of Statement, not Connection, and is about batching. - C. Closing a connection does not group the updates.