happy happy - 1 year ago 53
Java Question

How to execute multiple SQL statements from java

I want to execute the multiple queries or job in one execute.
Something like this

String query="select * from tab1;insert into tab1 values(...);update tab1..;delete from tab1...;"
Statement st = con1.createStatement();
ResultSet rs = st.executeQuery(query);

Or multiple select queries.Queries will be dynamic.

But I am not able to do this.What is the way to run multiple queries separated by semi colon.

Answer Source

you can achieve that using Following example uses addBatch & executeBatch commands to execute multiple SQL commands simultaneously.

Batch Processing allows you to group related SQL statements into a batch and submit them with one call to the database. reference

When you send several SQL statements to the database at once, you reduce the amount of communication overhead, thereby improving performance.

  • JDBC drivers are not required to support this feature. You should use the DatabaseMetaData.supportsBatchUpdates() method to determine if the target database supports batch update processing. The method returns true if your JDBC driver supports this feature.
  • The addBatch() method of Statement, PreparedStatement, and CallableStatement is used to add individual statements to the batch. The executeBatch() is used to start the execution of all the statements grouped together.
  • The executeBatch() returns an array of integers, and each element of the array represents the update count for the respective update statement.
  • Just as you can add statements to a batch for processing, you can remove them with the clearBatch() method. This method removes all the statements you added with the addBatch() method. However, you cannot selectively choose which statement to remove.


import java.sql.*;

public class jdbcConn {
   public static void main(String[] args) throws Exception{
      Connection con = DriverManager.getConnection

      Statement stmt = con.createStatement
      String insertEmp1 = "insert into emp values
      String insertEmp2 = "insert into emp values
      String insertEmp3 = "insert into emp values
      stmt.addBatch(insertEmp1);//inserting Query in stmt
      ResultSet rs = stmt.executeQuery("select * from emp");
      System.out.println("rows before batch execution= "
      + rs.getRow());
      System.out.println("Batch executed");
      rs = stmt.executeQuery("select * from emp");
      System.out.println("rows after batch execution= "
      + rs.getRow());

refer http://www.tutorialspoint.com/javaexamples/jdbc_executebatch.htm

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download