您现在的位置是:首页 >学无止境 >解决jdbc连接不释放的问题,将conn改为局部创建,用完后立马关闭。网站首页学无止境
解决jdbc连接不释放的问题,将conn改为局部创建,用完后立马关闭。
话不多说直接上代码:
public class ApplyInfoDao {
Connection conn = null;
public ApplyInfoDao()
{
//conn = this.getConn(); 注释后改为在每次使用时建立连接
}
public void close()
{
try {
if( !conn.equals(null))
{
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public Connection getConn()
{
try
{
Class.forName("oracle.jdbc.OracleDriver");
String dburl = "jdbc:oracle:thin:@172.16.5.111:1521/yyyappointment";
String userName = "xxx;
String passWord = "xx";
conn = DriverManager.getConnection(dburl,userName,passWord);
}
catch(Exception e)
{
e.printStackTrace();
}
return conn;
}
public List<HashMap> selectApplyMain(String code) {
String sql = "select * from MTS_REQ_DESC where ID_REQ_PAPER_DESC = '"+code+"'" ;
List<HashMap> list = new ArrayList();
try {
conn = this.getConn();//关键点使用前才建立
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(sql);
ResultSetMetaData rsmd = rs.getMetaData();
while(rs.next())
{
HashMap map = new HashMap();
int i = rsmd.getColumnCount();
for(int j=1;j<=i;j++)
{
if(!rsmd.getColumnName(j).equals("ID"))
{
map.put(rsmd.getColumnName(j), rs.getString(j)==null?"":rs.getString(j));
}
else
{
map.put("id", rs.getString(j));
}
}
list.add(map);
}
rs.close();
st.close();
} catch (SQLException e) {
System.out.println("--"+sql);
e.printStackTrace();
} //关键点使用后关闭
finally
{
this.close();
}
return list;
}
}