如何从java执行多个SQL语句

时间:2012-06-07 09:43:50

标签: java jdbc

我想在一次执行中执行多个查询或作业。 像这样的东西 例如:

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

或多个选择查询。查询将是动态的。

但是我无法做到这一点。运行以半冒号分隔的多个查询的方法是什么。

2 个答案:

答案 0 :(得分:36)

你可以使用以下示例使用addBatch& executeBatch命令可同时执行多个 SQL 命令。

批处理允许您将相关的SQL语句分组到批处理中,并通过一次调用数据库来提交它们。 reference

当您一次向数据库发送多个SQL语句时,可以减少通信开销,从而提高性能。

  • JDBC驱动程序不需要支持此功能。您应该使用DatabaseMetaData.supportsBatchUpdates()方法来确定目标数据库是否支持批量更新处理。如果JDBC驱动程序支持此功能,则该方法返回true。
  • Statement,PreparedStatement和CallableStatement的 addBatch()方法用于向批处理添加单个语句。 executeBatch()用于开始执行组合在一起的所有语句。
  • executeBatch()返回一个整数数组,数组的每个元素代表相应更新语句的更新计数。
  • 就像您可以向批处理中添加语句进行处理一样,您可以使用 clearBatch()方法删除它们。此方法删除使用addBatch()方法添加的所有语句。但是,您无法有选择地选择要删除的语句。

示例:

import java.sql.*;

public class jdbcConn {
   public static void main(String[] args) throws Exception{
      Class.forName("org.apache.derby.jdbc.ClientDriver");
      Connection con = DriverManager.getConnection
      ("jdbc:derby://localhost:1527/testDb","name","pass");

      Statement stmt = con.createStatement
      (ResultSet.TYPE_SCROLL_SENSITIVE,
      ResultSet.CONCUR_UPDATABLE);
      String insertEmp1 = "insert into emp values
      (10,'jay','trainee')";
      String insertEmp2 = "insert into emp values
      (11,'jayes','trainee')";
      String insertEmp3 = "insert into emp values
      (12,'shail','trainee')";
      con.setAutoCommit(false);
      stmt.addBatch(insertEmp1);//inserting Query in stmt
      stmt.addBatch(insertEmp2);
      stmt.addBatch(insertEmp3);
      ResultSet rs = stmt.executeQuery("select * from emp");
      rs.last();
      System.out.println("rows before batch execution= "
      + rs.getRow());
      stmt.executeBatch();
      con.commit();
      System.out.println("Batch executed");
      rs = stmt.executeQuery("select * from emp");
      rs.last();
      System.out.println("rows after batch execution= "
      + rs.getRow());
   }
} 

参考http://www.tutorialspoint.com/javaexamples/jdbc_executebatch.htm

答案 1 :(得分:4)

我不确定您是否要在一个请求语句中发送两个SELECT语句,因为您可能无法同时访问ResultSet个。数据库可能只返回最后的结果集。

多个结果集

但是,如果你正在调用一个你知道可以返回多个结果集的存储过程,那么这样就可以了。

CallableStatement stmt = con.prepareCall(...);
try {
...

boolean results = stmt.execute();

while (results) {
    ResultSet rs = stmt.getResultSet();
    try {
    while (rs.next()) {
        // read the data
    }
    } finally {
        try { rs.close(); } catch (Throwable ignore) {}
    }

    // are there anymore result sets?
    results = stmt.getMoreResults();
}
} finally {
    try { stmt.close(); } catch (Throwable ignore) {}
}

多个SQL语句

如果您正在讨论多个SQL语句并且只有一个SELECT,那么您的数据库应该能够支持一个String的SQL。例如,我在Sybase

上使用了类似的东西
StringBuffer sql = new StringBuffer( "SET rowcount 100" );
sql.append( " SELECT * FROM tbl_books ..." );
sql.append( " SET rowcount 0" );

stmt = conn.prepareStatement( sql.toString() );

这取决于数据库支持的语法。在此示例中,请注意添加语句spaces填充语句,以便在staments之间留出空白。