gpt4 book ai didi

java - SQLServerException 结果集已关闭

转载 作者:行者123 更新时间:2023-12-02 04:58:08 28 4
gpt4 key购买 nike

我收到“SQLServerException:0 结果集已关闭”。结果集已关闭。@java.lang.Thread:run:722' 在以下代码中。

我可以看到我没有关闭语句或结果集,那么为什么我会收到此异常。

有谁可以帮忙吗??提前致谢

private boolean isConnectionValid(Connection connection){
//SQL statement to execute the query.
Statement statement = null;
//resultSet receives the result of statement execution.
ResultSet resultSet = null;
//detect the connectivity.
try{
//create a statement.
statement = connection.createStatement();
//define the specific query after the statement is created.
String query = databaseType == DatabaseType.ORACLE? "select 1 from dual" : "select 1";
//apply the statement to execute the query.
resultSet = statement.executeQuery(query);
// if the resultSet.next() returns true, the connection is fine. Otherwise the connection is invalid.
return resultSet.next();
}catch(SQLException e){
//If any SQL Exception is caught, the connection is invalid as well.
Common.logException2(getLogger(), e, null);
return false;
}finally{
//finally close statement and resultSet to prevent cursor leak if any of them is not null.
Common.closeStatementAndResultSet(statement, resultSet, getLogger());
}

我使用 isConnectionValid 方法的一个示例如下:

public boolean execute(Logger logger) throws SQLException {
try {
if( !query.toUpperCase().startsWith("SELECT") ) {
queryLoggerInfo(database.getDbName() + " " + this);
}
return statement.execute();
} catch (SQLException e) {
if (database.isConnectionValid(connectionId)){
//log it
} else {
// other log methods
}
throw e;
}
}

最佳答案

正在调用finally block before the return is evaluated ,当您返回值时,结果集已经关闭。

尝试以这种方式更改代码:

boolean output = resultSet.next();
return output;

请引用this question

编辑:

这始终是事实。我创建了一个测试来证明我的观点:

public class Testing {

public static void main(String[] args) {
Testing t = new Testing();

System.out.println("Test1: " + t.getStringListValue());
System.out.println("Test2: " + t.getStringList().size());
}

public String getStringListValue() {
List<String> stringList = new ArrayList<String>();

try {
stringList.add("a");
stringList.add("b");
stringList.add("c");

return stringList.get(2);
} catch (Exception e) {

} finally {
stringList.clear();
}

return null;
}

public List<String> getStringList() {
List<String> stringList = new ArrayList<String>();

try {
stringList.add("a");
stringList.add("b");
stringList.add("c");

return stringList;
} catch (Exception e) {

} finally {
stringList.clear();
}

return null;
}
}

在 getStringList() 方法中,我在finally block 中调用clear(),当我尝试获取大小时,我按预期得到了 0。

另一方面,在 getStringListValue() 中,我也调用了clear,但我按照您的建议返回了列表中第二个元素的值,并且可以打印它的值。

这里发生的是,在返回行中创建了一个指向 String 对象的指针,并接收了数组中第二个元素的值。因此,finally block 中的clear() 会清除List,但返回的String 会保留复制的值。

关于java - SQLServerException 结果集已关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28562351/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com