如何从java执行多个SQL语句

hap*_*ppy 27 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); 
Run Code Online (Sandbox Code Playgroud)

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

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

Hem*_*lia 37

您可以使用以下示例实现该功能以下示例使用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());
   }
} 
Run Code Online (Sandbox Code Playgroud)

请参阅http://www.tutorialspoint.com/javaexamples/jdbc_executebatch.htm

  • 我不确定你是在回答这个问题.您正在讨论批处理的INSERT语句,并且该问题与多个SELECT语句有关,因此必须处理ResultSet (2认同)

Bra*_*rad 5

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

多个结果集

但是,如果您正在调用一个您知道可以返回多个结果集的存储过程,这样的事情会起作用

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) {}
}
Run Code Online (Sandbox Code Playgroud)

多条 SQL 语句

如果您谈论的是多个 SQL 语句并且只有一个 SELECT,那么您的数据库应该能够支持其中一个StringSQL。例如我在 Sybase 上使用过这样的东西

StringBuffer sql = new StringBuffer( "SET rowcount 100" );
sql.append( " SELECT * FROM tbl_books ..." );
sql.append( " SET rowcount 0" );

stmt = conn.prepareStatement( sql.toString() );
Run Code Online (Sandbox Code Playgroud)

这将取决于您的数据库支持的语法。在此示例中,请注意spaces语句的附加填充,以便在两句之间留有空格。

  • 最初的问题涉及非同质语句 - 因此这个答案比涉及批处理执行的答案更正确。 (2认同)