如何从java执行多个SQL语句

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

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驱动程序不需要支持此function。 您应该使用DatabaseMetaData.supportsBatchUpdates()方法来确定目标数据库是否支持批量更新处理。 如果JDBC驱动程序支持此function,则该方法返回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 。 数据库可能只返回最后的结果集。

多个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 ,以便在staments之间存在空白。