【发布时间】:2012-07-03 07:09:09
【问题描述】:
我有一个 java 库来查询 mysql database,将 ResultSet 返回给另一个 Java 函数。由于mysql超时问题,我使用c3p0 pool来实现查询。
cpds = new ComboPooledDataSource();
cpds.setDriverClass("com.mysql.jdbc.Driver");
cpds.setJdbcUrl(url);
cpds.setUser(user);
cpds.setPassword(passwd);
cpds.setMaxPoolSize(maxPoolSize);
cpds.setMinPoolSize(minPoolSize);
cpds.setAcquireIncrement(20);
public ResultSet fetch() {
PreparedStatement pst = null;
ResultSet rs = null;
String query = null;
Connection conn = null;
try {
conn = cpds.getConnection();
query = "...";
pst = conn.prepareStatement(query);
rs = pst.executeQuery();
} catch (SQLException ex) {
Logger lgr = Logger.getLogger(Query.class.getName());
lgr.log(Level.SEVERE, ex.getMessage(), ex);
}finally {
try {
if(conn != null) {
conn.close();
}
} catch (SQLException ex) {
Logger lgr = Logger.getLogger(Query.class.getName());
lgr.log(Level.SEVERE, ex.getMessage(), ex);
}
}
return rs;
}
}
我收到了这个错误
SEVERE: Operation not allowed after ResultSet closed java.sql.SQLException: Operation not allowed after ResultSet closed
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1075)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:989)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:984)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:929)
at com.mysql.jdbc.ResultSetImpl.checkClosed(ResultSetImpl.java:795)
at com.mysql.jdbc.ResultSetImpl.next(ResultSetImpl.java:7146)
at com.mchange.v2.c3p0.impl.NewProxyResultSet.next(NewProxyResultSet.java:622)
原因很明显,但我在想什么是调用 Mysql 查询并在函数中获取结果的最佳方法。
【问题讨论】:
-
这个问题的一些变体以前已经被问过很多次了,例如见stackoverflow.com/questions/4106606/… 此外,c3p0 与这个问题无关。
-
错误来自哪一行?
-
问题是上层函数get ResultSet Object rs,而不是Connection Object conn,可以做rs.close(),但是不能用conn.close()。我的以下问题是当我执行 rs.close() 时,连接也会被释放吗?因为我需要释放连接,并把它放回连接池。