我有一个 Java 中的
CachedRowSet
对象。由于 CachedRowSets
与数据库断开连接,是否需要关闭它们,或者将它们放入 try-with-resources 块中?我的 IDE 建议我应该这样做。
这是我使用它的方式,我从查询中填充
CachedRowSet
(并对PreparedStatement
和ResultSet
对象使用try-with-resources)
public static void resultSetParsing(Connection con) throws Exception {
String sqlStatement = " select id, name from TestTable ";
CachedRowSet cachedRowSet = null;
try(PreparedStatement pstmt = con.prepareStatement(sqlStatement)){
try(ResultSet rs = pstmt.executeQuery()){
cachedRowSet = RowSetProvider.newFactory().createCachedRowSet();
// Fill the CachedRowSet from the ResultSet
cachedRowSet.populate(rs);
}
}
// I am disconnected from the DB at this point
while(cachedRowSet.next()){
System.out.println("Found item: " + cachedRowSet.getString("id") + " " + cachedRowSet.getString("name"));
}
}
我最后没有关闭它有什么关系吗?我想正确使用这个对象。
通常,如果您重用这些对象,则不需要关闭它们。但无论如何,强烈建议您这样做。
即使它现在没有内存泄漏或其他副作用,你也不能确定它在库的下一个版本中仍然可以工作。