In this example we will show how to batch update using statement.
Source Code
package com.beginner.examples;
import com.mysql.jdbc.Driver;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class BatchUpdateExample {
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);
Statement s = conn.createStatement();
s.addBatch("update user set host='2' WHERE user = '1' ");
s.addBatch("update user set host='1' WHERE user = '2' ");
s.executeBatch();
System.out.println("OK");
}
catch (SQLException e) {
e.printStackTrace();
}
}
}
Output:
OK
References
Imported packages in Java documentation: