通常的操作方法
public List<Category> queryCategory(String queryStr) throws SQLException {
ArrayList<Category> catList = new ArrayList<Category>();
PreparedStatement pstmt = DBUtil.getConnection().prepareStatement(
queryStr);
if (pstmt == null) {
return catList;
} else {
ResultSet rst = pstmt.executeQuery();
while (rst.next()) {
Category c = new Category();
c.setCategoryId(rst.getInt("CATEGORY_ID"));
c.setCategoryName(rst.getString("CATEGORY_NAME"));
c.setCategoryParent(rst.getInt("PARENT_ID"));
catList.add(c);
}
rst.close();
pstmt.getConnection().close();
}
return catList;
}
這種方式是不保險(xiǎn)的方式,因?yàn)榇颂幉⒉惶幚懋惓#遣慌懦龝?huì)發(fā)生異常。
假設(shè)在黑體代碼部分發(fā)生異常,那么下面的代碼并不會(huì)執(zhí)行,也就是說(shuō),rst,pstmt,con都不會(huì)關(guān)閉掉。
所以導(dǎo)致的結(jié)果是這些資源得不到釋放。
解決的方法,就是在最后用finally去解決問(wèn)題
PreparedStatement pstmt = null;
ResultSet rst = null;
try {
pstmt = this.getPstmt(queryStr);
rst = pstmt.executeQuery();
while (rst.next()) {
Category c = new Category();
c.setCategoryId(rst.getInt("CATEGORY_ID"));
c.setCategoryName(rst.getString("CATEGORY_NAME"));
c.setCategoryParent(rst.getInt("PARENT_ID"));
catList.add(c);
}
} catch (SQLException e) {
throw e;
}finally{
if(rst!=null){
rst.close();
}
if(pstmt!=null){
pstmt.close();
}
if(this.getCon()!=null&&this.getCon().getAutoCommit()){
this.getCon().close();
}
}
這樣,無(wú)論在那個(gè)地方發(fā)生了異常,都能讓資源得到釋放。
|----------------------------------------------------------------------------------------|
版權(quán)聲明 版權(quán)所有 @zhyiwww
引用請(qǐng)注明來(lái)源 http://www.aygfsteel.com/zhyiwww
|----------------------------------------------------------------------------------------|