使用JDBC驱动程序,如何在不连续打开和关闭连接的情况下使用来自不同查询的多个结果集,因为它正在提取w.e我需要并将其传递给另一个方法。每次打开一个新的conn,语句和结果集
public static void OppQuery() {
Connection conn = null;
Statement stmt = null;
ResultSet result_set = null;
try {
Class.forName(JDBC_DRIVER);
conn = DriverManager.getConnection(DB_URL);
stmt = conn.createStatement();
String emailInfoQuery = "FROM WHERE";
}
public static void addQuery(String latestRenewalId) {
Connection conn = null;
Statement stmt = null;
ResultSet result_set = null;
try {
Class.forName(JDBC_DRIVER);
conn = DriverManager.getConnection(DB_URL);
stmt = conn.createStatement();
String new_AddressLine1, new_AddressLine2;
new_AddressLine1=new_AddressLine2="";
int new_ChannelOption= 0;
}
我尝试在一个方法中使用多个结果集,但它一直抛出异常,说结果集已关闭。我对SqlServver没有多少经验,所以任何指导都会有所帮助: - )
答案 0 :(得分:2)
在JDBC中,当连接处于自动提交模式(这是默认设置)时,任何语句的执行都将提交上一个事务并关闭同一连接上的所有打开结果集(假设可保持性为{{1实际上isn't the default for SQL Server)。当您需要打开多个结果集时,您需要禁用自动提交(或使用ResultSet.CLOSE_CURSORS_AT_COMMIT
)和,您需要使用多个ResultSet.HOLD_CURSORS_OVER_COMMIT
对象。 JDBC要求同一Statement
对象上的新执行关闭同一语句中的任何其他打开结果集。
所以
Statement
)Connection.setAutoCommit(false)
个对象打开Statement
s 答案 1 :(得分:0)
继Mark的答案之后,由于Microsoft SQL Server JDBC驱动程序似乎默认创建“可保持”ResultSet对象,因此在启用AutoCommit时,以下测试代码可以正常工作:
import java.sql.*;
public class SqlServerTest {
public static void main(String[] args) {
try {
String connectionUrl =
"jdbc:sqlserver://localhost:52865;" +
"databaseName=myDb;" +
"integratedSecurity=true";
Connection con = DriverManager.getConnection(connectionUrl);
System.out.println(String.format("con.getAutoCommit returned %s", con.getAutoCommit()));
Statement st1 = con.createStatement();
ResultSet rs1 = st1.executeQuery("SELECT id FROM odds");
rs1.next();
System.out.println(String.format("value from rs1: %d", rs1.getInt(1)));
Statement st2 = con.createStatement();
ResultSet rs2 = st2.executeQuery("SELECT id FROM evens");
rs2.next();
System.out.println(String.format("value from rs2: %d", rs2.getInt(1)));
rs1.next();
System.out.println(String.format("value from rs1: %d", rs1.getInt(1)));
rs2.next();
System.out.println(String.format("value from rs2: %d", rs2.getInt(1)));
rs2.close();
rs1.close();
con.close();
} catch(Exception e) {
e.printStackTrace();
}
}
}
对于名为[odds] ...
的表格中的测试数据id description
-- -----------
1 one
3 three
5 five
......和[evens] ......
id description
-- -----------
2 two
4 four
6 six
...控制台输出是:
con.getAutoCommit returned true
value from rs1: 1
value from rs2: 2
value from rs1: 3
value from rs2: 4