我想在一次执行中执行多个查询或作业。 像这样的东西 例如:
String query="select * from tab1;insert into tab1 values(...);update tab1..;delete from tab1...;"
Statement st = con1.createStatement();
ResultSet rs = st.executeQuery(query);
或多个选择查询。查询将是动态的。
但是我无法做到这一点。运行以半冒号分隔的多个查询的方法是什么。
答案 0 :(得分:36)
你可以使用以下示例使用addBatch& executeBatch命令可同时执行多个 SQL 命令。
批处理允许您将相关的SQL语句分组到批处理中,并通过一次调用数据库来提交它们。 reference
当您一次向数据库发送多个SQL语句时,可以减少通信开销,从而提高性能。
DatabaseMetaData.supportsBatchUpdates()
方法来确定目标数据库是否支持批量更新处理。如果JDBC驱动程序支持此功能,则该方法返回true。executeBatch()
用于开始执行组合在一起的所有语句。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之间留出空白。