10.30.07

使用JDBC后记得关闭并释放数据库连接资源噢:)

Posted in Java, JobTong at 13:34 Author:仲远 浏览量: 902

标签:, , , , ,

前几天做Jobtong的地点规范化工作,发现运行程序后一段时间居然出现 out of memory ! 这让我惊诧不已,1.5G的内存,跑这样的一个小程序居然就内存溢出了?于是随即check了一下代码,发现是写程序的时候图方便,直接建立了一个conn之后就一直使用,没有任何释放过程,Statement使用完之后也没有释放资源。这样当数据查询一多之后,内存需求不断增加,原来用完的资源又没有释放,结果就溢出了。

从网上找了一段代码,供大家参考:

  1. Connection conn = null;
  2.   ResultSet rs = null;
  3.   PreparedStatement pss = null;
  4.   try 
  5.   { 
  6.       conn = dataSource.getConnection(USERID,PASSWORD);
  7.       pss = conn.prepareStatement("SELECT SAVESERIALZEDDATA
  8.       FROM SESSION.PINGSESSION3DATA WHERE SESSIONKEY = ?");
  9.       pss.setString(1,sessionKey);
  10.       rs = pss.executeQuery();
  11.       pss.close();
  12.       conn.close();
  13.   } 
  14.   catch (Throwable t) 
  15.   { 
  16.       // Insert Appropriate Error Handling Here
  17.   } 
  18.   finally 
  19.   { 
  20.       // The finally clause is always executed - even in error
  21.       // conditions PreparedStatements and Connections will always be closed
  22.       try 
  23.       { 
  24.           if (pss != null) 
  25.              pss.close();
  26.       } 
  27.       catch(Exception e) {} 
  28.   
  29.       try 
  30.       { 
  31.           if (conn != null) 
  32.               conn.close();
  33.       } 
  34.       catch (Exception e){} 
  35.    } 
  36. }

Leave a Comment

*
To prove you're a person (not a spam script), type the security text shown in the picture. Click here to regenerate some new text.
Click to hear an audio file of the anti-spam word