WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Java JDBC · Intermediate · question 34 of 100

Can you describe the process of performing batch updates using PreparedStatement?

📕 Buy this interview preparation book: 100 Java JDBC questions & answers — PDF + EPUB for $5

Performing batch updates with PreparedStatement involves executing a set of queries or updates together in a single transaction, which can enhance performance and reduce overhead. Here’s an example of how to do so step-by-step:

1. Create a connection to the database using a JDBC driver, as you normally would. For example:

    Connection connection = DriverManager.getConnection(url, user, password);

2. Create a PreparedStatement for the query or update that you want to perform. In the case of batch updates, you’ll use a ‘addBatch()‘ method to add multiple sets of parameters to a single PreparedStatement object. For example:

    PreparedStatement ps = connection.prepareStatement("INSERT INTO mytable (name, age) VALUES (?, ?)");
    ps.setString(1, "John");
    ps.setInt(2, 30);
    ps.addBatch();
    
    ps.setString(1, "Mary");
    ps.setInt(2, 25);
    ps.addBatch();
    
    ps.setString(1, "Peter");
    ps.setInt(2, 40);
    ps.addBatch();

3. Once all the batches have been added to the PreparedStatement object, execute them all at once using the ‘executeBatch()‘ method. This method returns an array of integers that specifies the number of rows affected by each update. For example:

    int[] result = ps.executeBatch();

4. Commit the changes to the database using the ‘commit()‘ method of the connection. If an error occurs during the batch update, a SQLException will be thrown and the ‘rollback()‘ method should be called instead. For example:

    connection.commit();

And that’s it! By using PreparedStatement and its batch update functionality, you can perform a set of queries or updates in a more efficient and optimized way.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Java JDBC interview — then scores it.
📞 Practice Java JDBC — free 15 min
📕 Buy this interview preparation book: 100 Java JDBC questions & answers — PDF + EPUB for $5

All 100 Java JDBC questions · All topics