繁体   English   中英

如何从Java执行多个SQL语句

[英]How to execute multiple SQL statements from java

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

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

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

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

您可以使用以下示例来实现这一点,该示例使用addBatch和executeBatch命令同时执行多个SQL命令。

批处理允许您将相关的SQL语句分组为一个批处理,并通过一次调用将其提交给数据库。 参考

当您一次向数据库发送多个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

我不确定您是否要在一个请求语句中发送两个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,那么您的数据库应该能够支持一个SQL String 例如,我在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 ,以便在各步之间有空白。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM