I had this problem with Java and Postgresql. I resolved this issue using the connection PGPoolingDataSource and Close.
This is how I built my classes:
// Factory Class Connection:
public class FacConn { public static PGPoolingDataSource getConnection2() { PGPoolingDataSource source = new PGPoolingDataSource(); source.setServerName("local"); source.setPortNumber(5432); source.setDatabaseName("mydbname"); source.setUser("LoginUser"); source.setPassword("password"); source.setAssumeMinServerVersion("9.0"); source.setConnectTimeout(50000); return source; } }
// class userDAO - a class for interacting with the database
public class UsuarioDAO { private PGPoolingDataSource poolDS = FabConexao.getConnection2(); private Connection con = null; public User searchById(Integer id){ try{con = poolDS.getConnection();} catch (SQLException e){throw new RuntimeException(e);} String sql = "Select * from people where id_people=?"; ResultSet rs = null; try (PreparedStatement smtm = con.prepareStatement(sql)){ smtm.setInt(1, id); rs = smtm.executeQuery(); People people = new People(); if(rs.next()){ people.setId_People(rs.getInt("id_people")); people.setFirtname(rs.getString("firstname")); people.setLastname(rs.getString("lastname")); people.setAge(rs.getInt("age")); people.setActiv(rs.getBoolean("activ")); } smtm.close(); return people; } catch (SQLException e){ e.printStackTrace(); System.err.println( e.getClass().getName()+": "+ e.getMessage() ); } finally { if (rs != null) { try {rs.close();} catch (SQLException e) { } } poolDS.close(); } return null; }
HectorBonilha
source share