How to properly close MySql database connection
<p>In my web application I have separate classes DataAccess.java and DBUtils.java. </p>

<p>I have following code in DBUtils.jva</p>

<pre><code>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;
</code></pre>

<p>I have following code in DataAccess.java class</p>

<pre><code>public static List&lt;Company&gt; getAllCompanies(){
    List&lt;Company&gt; ls = new LinkedList&lt;&gt;();

    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;
}
</code></pre>

<p>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,</p>

<p>com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Data source rejected establishment of connection,  message from server: "Too many connections"</p>

<p>Could someone please advise me on how to properly close database connection in this case. </p>