In my web application I have separate classes DataAccess.java and DBUtils.java.
I have following code in DBUtils.jva
public static PreparedStatement getPreparedStatement(String sql) throws ClassNotFoundException, SQLException{
PreparedStatement ps = null;
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/company";
String user = "root";
String pass = "root";
Connection con = DriverManager.getConnection(url, user, pass);
ps = con.prepareStatement(sql);
return ps;
I have following code in DataAccess.java class
public static List<Company> getAllCompanies(){
List<Company> ls = new LinkedList<>();
try {
String sql = "select * from company";
ResultSet rs = DBUtils.getPreparedStatement(sql).executeQuery();
while (rs.next()){
Company cp = new Company (rs.getInt(1), rs.getString(2), rs.getInt(3),rs.getTimestamp(9));
ls.add(cp);
}
rs.close();
} catch (ClassNotFoundException | SQLException ex) {
Logger.getLogger(DataAccess.class.getName()).log(Level.SEVERE, null, ex);
}
return ls;
}
And I am calling getAllCompanies function from a different servlet. I don't know how to properly close database connection as it is opened in one class and called from another class. My web application keeps crashing due to too many open connections to database, the error says,
com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Data source rejected establishment of connection, message from server: "Too many connections"
Could someone please advise me on how to properly close database connection in this case.