Problems with the connection to mysql with java

1

My problem is that my java application generates too many connections without control. In the first instance I thought it was because I was not closing the connections correctly, but the problem is not solved. Any other option to be able to close those connections without control?

In this fragment is the connection code (both the connection method and the disconnection method)

public Connection MySQLConnection(String user, String pass, String db_name)  {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conexion = DriverManager.getConnection("jdbc:mysql://localhost:3306/" + db_name, user, pass);
            System.out.println("Conectado");
//            JOptionPane.showMessageDialog(null, "Se ha iniciado la conexión con el servidor de forma exitosa");
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(conexion.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage());
        }
        return conexion;
    }
    public  void closeConnection() {
        try {
            conexion.close();
//            JOptionPane.showMessageDialog(null, "Se ha finalizado la conexión con el servidor");
        } catch (SQLException ex) {
            Logger.getLogger(conexion.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

And this is the code of an example where I make the connection and disconnection of the database to perform an operation to load a combobox.

public void comboboxar(JComboBox<String> combo){
        con =new conexion();
        Connection c=con.MySQLConnection("root","", "emcisa");
        try {
            
            Statement st3=c.createStatement();
            ResultSet rs2=st3.executeQuery("SELECT id_productos FROM productos WHERE baja=0");
            combo.removeAllItems();
            while(rs2.next()){
                combo.addItem(rs2.getString(1));
            }
        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }finally {
            con.closeConnection();
        }
    
asked by Jose Imhoff 23.02.2018 в 15:10
source

1 answer

1

When you open a connection to a DB in this way the workaround to complete the connection is closing the resultset, then the statement, and in the end the connection to keep it as clean as possible, you are only closing the connection and you are leaving in the execution the last two.

Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;

try{
//.....
}catch(exception e){
//....
}finally{
    try { rs.close(); } catch (Exception e) { /* ignored */ }
    try { ps.close(); } catch (Exception e) { /* ignored */ }
    try { conn.close(); } catch (Exception e) { /* ignored */ }
}

Apache has a utility to summarize this process: link

I also recommend that you use tools like jdbcTemplate, or ORMs like JPA.

    
answered by 09.12.2018 в 17:55