How to Batch Update Using PreparedStatement in Java


In this example we will show how to batch update using PreparedStatement.

Source Code

package com.beginner.examples;

import com.mysql.jdbc.Driver;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
  
    public class PrepareBatchUpdateExample {
        public static void main(String[] args) throws ClassNotFoundException {

        Class.forName("com.mysql.jdbc.Driver");

        try
        {
        	//database connection
            Connection conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/mysql", "root", "");

            // donnot auto commit 
            conn.setAutoCommit(false);
            PreparedStatement p = conn.prepareStatement("update user set host=? where user=?");
            p.setNString(1, "1");
            p.setNString(2, "1");
            p.addBatch();
            p.setNString(1, "2");
            p.setNString(2, "2");
            p.addBatch();
            p.executeBatch();
            conn.commit();
            System.out.println("OK");
        }
        catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

Output:

OK

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments