JDBC Batch Tutorial
In this tutorial, we will see “how to execute multiple queries using a single JDBC Statement“.
- Add allowMultiQueries=true to mysql url
- Get the database connection
- Create Statement
- Use method statement.addBatch(sql) to add list of SQL statements.
- invoke statement.executeBatch() to execute all SQL queries
JDBC Batch Tutorial java code:
String url = "jdbc:mysql://localhost:3306/database_name?autoReconnect=true&allowMultiQueries=true";
String driver = "com.mysql.jdbc.Driver";
String userName= "root";
String password= "abc";
Class.forName(driver).newInstance();
String sql1= "delete from table1 where id="+101;
String sql2= "delete from table2 where id="+101;
String sql3= "delete from table3 where id="+101;
String sql4= "insert into auditlog values(101, 'deleted from table1')";
Connection connection = null;
Statement statement = null;
try{
connection = DriverManager.getConnection(url, userName, password);
statement = connection.createStatement();
statement.addBatch(sql1);
statement.addBatch(sql2);
statement.addBatch(sql3);
statement.addBatch(sql4);
statement.executeBatch();
}catch(Exception e){
e.printStackTrace();
}
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}