我写了一个查询,如下所示 -
Connection dbConnection = null;
PreparedStatement preparedStatement = null;
ResultSet rs = null;
try {
String fetchOneSQL = "select p.NAME from PAPER p where p.PAPERID="+paperId;
dbConnection = icrudResultAnalysis.getConnection();
preparedStatement = dbConnection.prepareStatement(fetchOneSQL);
rs = preparedStatement.executeQuery();
while (rs.next()) {
Paper paper=new Paper();
paper.setName(rs.getString(NAME));
}
// get new records list
preparedStatement=null;
rs=null;
String getListSql="select ib.NAME from ITEMBANK ib where ib.ITEMBANKID="+itemBankId;
preparedStatement = dbConnection.prepareStatement(getListSql);
rs = preparedStatement.executeQuery();
while (rs.next()) {
ItemBank itemBankObj=new ItemBank();
itemBankObj.setName(rs.getString(NAME));
listItemBanks.add(itemBankObj);
}
rs.close();
preparedStatement.close();
dbConnection.close();
} catch (Exception e) {
LOGGER.error("Exception Occured while fetching All record: "
+ e.getMessage());
} finally {
try{
if (rs!=null){
rs.close();
}
}catch(SQLException e)
{
LOGGER.error(RESULTSETCLOSEEXCEPTION + e.getMessage());
}
try {
if (preparedStatement != null) {
preparedStatement.close();
}
} catch (SQLException e) {
LOGGER.error(STATEMENTCLOSEEXCEPTION
+ e.getMessage());
}
try {
if (dbConnection != null) {
dbConnection.close();
}
} catch (SQLException e) {
LOGGER.error(CONNECTIONCLOSEEXCEPTION
+ e.getMessage());
}
}
在上面的代码中,我通过创建ResulSet rs =null将单个结果集用于两个 select 语句。这是好习惯吗?或者我每次都必须关闭 ResultSet?关闭 ResultSet 和使 ResultSet 为空有什么区别?