【发布时间】:2015-02-17 13:11:51
【问题描述】:
我收到 '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;
}
}
【问题讨论】:
-
看起来您并没有在任何地方打开连接。是 connection.Open 被调用了吗?
-
@gh9 是的,这是我正在做的检查的一部分。所以我正在打开连接并做一些事情。当我遇到一些错误/异常时,我会运行此方法来检查连接是否有效。
-
你调用的代码在哪里
.isConnectionValid(connection); -
@user1354678 我更新了描述。希望对您有所帮助...
-
提供完整的堆栈跟踪,以便我们知道在哪一行和哪个组件上抛出了这个异常。您的帖子目前令人困惑。在旁注中,您最好让连接池处理验证。 Commons DBCP 让您使用
validationQuery参数validationQuery="SELECT version();"来执行此操作。