JDBC Batch Tutorial

In this tutorial, we will see “how to execute  multiple queries using a single JDBC Statement“.

  1. Add allowMultiQueries=true to mysql url
  2. Get the database connection
  3. Create Statement
  4. Use method  statement.addBatch(sql) to add list of SQL statements.
  5. 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();
 }
 

Leave a Comment

Your email address will not be published. Required fields are marked *