Glassfish does not reuse JDBC Connections
我在glassfish Web服务器上使用JDBC连接池。我通过以下语句注入数据源:
1 2 | @Resource(lookup="database") DataSource db; |
我用来加载数据的代码看起来像这样:
1 2 3 4 5 6 7 8 9 10 11 12 | public ArrayList<Stuff> loadStuff()throws SQLException{ PreparedStatement ps = db.getConnection().prepareStatement("Select * from stufftable"); ResultSet rs = ps.executeQuery(); ArrayList<Stuff> stuffs= new ArrayList<Stuff>(); if(rs.next()){ Stuff stuff = new Stuff(); stuff.setString1(rs.getString("string1")); stuff.setString1(rs.getString("string1")); stuffs.add(stuff ); } return stuffs; } |
出于某种原因,glassfish不会重用数据库连接,因此我很快就用光了它们。
迟早我总是会收到此错误:
据我所知,在玻璃鱼上池化的概念是:我不应该在使用连接后关闭连接,因此在需要时其他某些东西可以重用该连接。当不再有连接需求时,Glassfish会自行关闭连接。
为什么我的程序每次都打开一个新连接?完成后,我必须对连接做些什么吗?
您仍然需要呼叫
编辑:或者,使用try-with-resources:
https://stackoverflow.com/a/8066594/212224
1 2 3 4 5 6 7 8 | Connection con = db.getConnection(); try { PreparedStatement ps = con.prepareStatement("Select * from stufftable"); ... } finally { // this returns the connection to the pool con.close(); } |