How to close the connection correctly with MySQL in Java when reading from the database to fill a JTable

0

I request in my program a phone number of origin, another destination and the duration. I keep it in the database, then I must read the database to fill a JTable but, you are giving me the following error:

  

mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException:       No operations allowed after connection closed.

Am I closing the connections incorrectly? What do I need?

This is my code:

// Agregar filas al JTable leyendo la base de datos
Connection conn = conexion.getConnection();
Statement st;

// Creamos un objeto de la clase ResultSet,
// la cual será la encargada de devolvernos los resultados de los registros
ResultSet rs;

// Crear sentencia SQL para seleccionar/obtener en la base de datos
String showTableSQL = "SELECT * FROM llamadas";

                try {
                    // Establecemos la comunicación entre nuestra aplicación java y la base de datos
                    st = conn.createStatement();

                    // Le pasamos al objeto de ResultSet el resultado de ejecutar la sentencia "query"
                    // Con "executeQuery" realizamos una consulta a la base de datos
                    rs = st.executeQuery(showTableSQL);

                    // En este bucle vamos recorriendo valores mientras existan
                    while (rs.next()) {
                        // Obtenemos el modelo del JTable
                        model = (DefaultTableModel) table.getModel();

                        // Agregamos las filas al JTable
                        // Con "getInt" y "getString" obtenemos los valores de las diferentes columnas pasandole el número de columna
                        model.addRow(new Object[]{
                                        Integer.toString(rs.getInt(1)),
                                        rs.getString(2),
                                        rs.getString(3),
                                        rs.getString(4),
                                        rs.getString(5),
                                        Integer.toString(rs.getInt(6)),
                                        Double.toString(rs.getDouble(7))
                                            });
                                        }

                    // Cerramos las conexiones, en orden inverso a su apertura
                    conn.close();
                    rs.close();
                    st.close();
                } catch (SQLException error) {
                    System.out.println("Error!, no se pudo llenar el JTable.\n" + error);;
                }

I have no idea why he says that the connection has been closed if I am requesting a new connection. Any help is welcome, thanks for everything and for your time.

    
asked by Robert Gomez 26.11.2016 в 04:21
source

1 answer

1

The problem is that if there is an exception before, the close() do not run.

Normally it should be in finally of try-catch , to make sure it is closed even if an exception is thrown.

Also, it's worth to close in reverse order (first rs, then st, then conn).

Make sure you do not throw an exception when closing. It would be unlikely, but it would be quite confusing.

  } catch (SQLException e) {
    ...
  } finally {
    try {
      rs.close();
    } catch (Exception e) {
      // LOG
    }

    try {
      st.close();
    } catch (Exception e) {
      // LOG
    }

    try {
      conn.close();
    } catch (Exception e) {
      // LOG
    }

If you use Java 7 or later, you can use the try-with-resources, which is already closed when you exit try

try (Connection conn = crearConexion();
     Statement st = conn.createStatement();
     ResultSet rs = st.executeQuery(showTableSQL);) {
    ... Leer resultset
} catch (SQLException e) {
    ...
}
    
answered by 26.11.2016 / 11:29
source