The server closes me connection with the mysql server

1

Good, I have an application made in java and mysql, after hours the connection is closed, I understand that by the global variable of the server mysql wait-timeout.

I have a class that creates the connection to the BBDD and then a class "manager" where I do all the queries and updates. I think the problem is that I do not close the connection and when I stay open, once the mysql timeout is fulfilled, it is cut ...

The thing is that I tried to create a connection in each method and close it but closing it and making a connection again gives me the error of no operations allowed after connection closed.

My class to create the connection is

public class SGBD {
private static Connection conn=null;
public static SGBD instance;
private String servidor;
private String IP;
private String user;
private String password;

private SGBD(String servidor, String IP,String user, String password){

    this.setServidor(servidor);
    this.setIP(IP);
    this.setUser(user);
    this.setPassword(password);

    try{
        try{
            Class.forName("com.mysql.jdbc.Driver");
            java.sql.DriverManager.registerDriver(new com.mysql.jdbc.Driver());
        }catch(Exception e){
            System.out.println("Driver no encontrado");
            System.exit(0);
        }
        conn=DriverManager.getConnection("jdbc:"+this.getServidor()+"://"+this.getIP(),this.getUser(),this.getPassword());
        System.out.println("Conexion establecida con exito.");
    }catch(Exception e){
        System.out.println("Error en la conexion, el mensaje es: "+e.getMessage());
        System.exit(2);
    }

}
public static boolean isConnected(){
    return !(conn==null);
}
public Connection getConn() {
    return conn;
}
public static SGBD getInstance(String servidor, String IP,String user, String password){
    if(isConnected()){
        return instance;
        }else{
            instance=new SGBD(servidor,IP,user,password);
            return instance;
        }
    }

And the class that generates queries is similar to this:

public class GestorBD {

Connection conn;

/**
 * Constructor de la clase
 * @param servidor
 * @param ip
 * @param username
 * @param password
 */
public GestorBD(String servidor, String ip, String username, String password){
    this.setConn(SGBD.getInstance(servidor, ip, username, password).getConn());
}
public GestorBD(){
    //Base de datos servidor remoto
    this.setConn(SGBD.getInstance("","","","").getConn());
    //Base de datos servidor local
    //this.setConn(SGBD.getInstance("","","","").getConn());
}

public Connection getConn(){
    return conn;    
}

public void setConn(Connection conn) {
    this.conn = conn;
}


/**
 * Obtener la lista de las inmobiliarias registradas en la BBDD
 * @return
 * @throws SQLException
 * @throws EmailIncorrectoException 
 * @throws LongitudCadenaException 
 */
public List <Inmobiliaria> getInmobiliarias() throws SQLException, LongitudCadenaException, EmailIncorrectoException{
    List <Inmobiliaria> lista = new ArrayList<Inmobiliaria>();
    this.getConn().createStatement().execute("USE 'mhs_simple_form'");
    Statement stm = this.getConn().createStatement();
    ResultSet rs = stm.executeQuery("select * from tbl_inmobiliaria ORDER BY nombre_inmobiliaria ASC");

    while(rs.next()){
        Inmobiliaria inmo = new Inmobiliaria(
                rs.getInt("id_inmobiliaria"),
                rs.getString("nombre_inmobiliaria"), 
                rs.getString("email_inmobiliaria"), 
                rs.getString("pass_inmobiliaria"), 
                rs.getString("telefono_inmobiliaria"), 
                rs.getInt("estado_inmobiliaria"));
        lista.add(inmo);
    }
    stm.close();
    rs.close();
    return lista;
}

I do not know where to close the connection since it gives me an error. Thank you very much for the help

    
asked by Cristian 03.09.2016 в 12:38
source

3 answers

2

The answer to your query, you should reopen it if you detect that it has been closed (you should change your code to verify this).

Now, in a java web environment it is usually advisable to leave the connection management to servlet container (as it is Tomcat ) or to application server through a pool of connections.

This frees you from managing connections, that is, creating connections, closing them and reopening them if necessary.

I suggest you look in detail at some tutorial like this and this other . And read the Tomcat documentation on JDBC connections

If a problem arises, go through SO-es and see how we help you.

    
answered by 03.09.2016 / 14:53
source
1

Well, it's already solved. With the pool of connections as you had mentioned, I have managed to make everything work perfectly without the need to complicate my connections!

The problem was in the connection declared as static, there was always the same and as the time of inactivity mysql cut it ...

In case someone serves you I put part of the code

The pool

public class Pool {

public BasicDataSource basicDataSource;

public String db = "db";
public String url = "jdbc:mysql://localhost:3306/" + db;
public String user = "user";
public String pass = "pass";

public Pool(){
    inicializeDataSource();
}

private void inicializeDataSource(){
    basicDataSource = new BasicDataSource();

    basicDataSource.setDriverClassName("com.mysql.jdbc.Driver");
    basicDataSource.setUsername(user);
    basicDataSource.setPassword(pass);
    basicDataSource.setUrl(url);
    basicDataSource.setMaxActive(150);

}

And the class to make querys and updates

public class GestorPoolBD {

private DataSource dataSource=null;

public GestorPoolBD(){
    dataSource = new Pool().basicDataSource;
}

/** Getters setters DataSource */
public void setDataSource (DataSource dataSource) {
    this.dataSource = dataSource;
}
public DataSource getDataSourcer(){
   return dataSource;
}

//------------------------------------------------------------

/**
 * Obtener la lista de las inmobiliarias registradas en la BBDD
 * @return
 * @throws SQLException
 * @throws EmailIncorrectoException 
 * @throws LongitudCadenaException 
 */
public List <Inmobiliaria> getInmobiliarias(){

    Connection conn = null;
    List <Inmobiliaria> lista = new ArrayList<Inmobiliaria>();
    try{
        conn = dataSource.getConnection();
        conn.createStatement().execute("USE 'db'");
        Statement stm = conn.createStatement();
        ResultSet rs = stm.executeQuery("select * from tbl_inmobiliaria ORDER BY nombre_inmobiliaria ASC");

        while(rs.next()){
            Inmobiliaria inmo = new Inmobiliaria(
                    rs.getInt("id_inmobiliaria"),
                    rs.getString("nombre_inmobiliaria"), 
                    rs.getString("email_inmobiliaria"), 
                    rs.getString("pass_inmobiliaria"), 
                    rs.getString("telefono_inmobiliaria"), 
                    rs.getInt("estado_inmobiliaria"));
            lista.add(inmo);
        }
        stm.close();
        rs.close();
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (LongitudCadenaException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (EmailIncorrectoException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }finally{
        try {
            if (conn != null && !conn.isClosed()){
                conn.close();
            }
        } catch (SQLException e) {
            System.out.println("Error cerrando la conexion");
            e.printStackTrace();
        }
    }
    return lista;
}

It is still necessary to capture possible errors but I have verified that the connections do not stay open and then die

Thank you very much for the suggestions!

    
answered by 05.09.2016 в 19:42
-1
  

after hours the connection is closed

Exactly, you can define a value in which if no operations are registered, the connection is closed.

When you get this message it is because you simply can not access the data within the Database simply because of what you say, the connection is closed.

  

no operations allowed after connection closed.

    
answered by 04.09.2016 в 06:48