0

I'm working on a project of package deliveries in Java.

I'm attempting to load two JComboBox components with data from a database and I'm getting the following errors.

Sack Trace

    Names : java.sql.SQLNonTransientConnectionException: No operations allowed after connection closed.
java.sql.SQLNonTransientConnectionException: No operations allowed after connection closed.
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:108)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:95)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:87)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:61)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:71)
    at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:73)
    at com.mysql.cj.jdbc.ConnectionImpl.prepareStatement(ConnectionImpl.java:1829)
    at com.mysql.cj.jdbc.ConnectionImpl.prepareStatement(ConnectionImpl.java:1732)
    at Modelo.UsuarioDAO.usuarios_combo(UsuarioDAO.java:178)
    at Presentacion.ListarEncomiendasAdmin$1.run(ListarEncomiendasAdmin.java:62)
    at java.awt.event.InvocationEvent.dispatch(Unknown Source)
    at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
    at java.awt.EventQueue.access$400(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)

Here's my code to fill the combo box, in a class named UsuarioDAO.

    public JComboBox usuarios_combo(){
         JComboBox cbox_usuarios = new JComboBox();
         try {

             String sql = "SELECT usu_ci FROM usuarios";
             Connection conn = this.getConexion(); // in here i have a message which prints ok if connection succeeded so i guess the problem won't be here
             PreparedStatement pst1 = conn.prepareStatement(sql);
             pst1.setQueryTimeout(5);
             ResultSet rs = pst1.executeQuery();

             while ((rs != null) && (rs.next())) {

                 String ci = rs.getString("usu_ci");
                 cbox_usuarios.addItem(ci);
             }

             pst1.close();
             rs.close();
             conn.close();

         }
         catch (Exception e) {
             System.err.println("Names : " + e.getClass().getName() + ": " + e.getMessage());
             e.printStackTrace();
         }        
         return cbox_usuarios;
     }

Then, in the frame where I want to load both combo boxes, I have the following code:

public class ListarEncomiendasAdmin extends JFrame {

    private JPanel contentPane;
    private JTextField txtEstado;
    private JTextField txtOrigen;
    private JTextField txtDestino;
    private static JTable tblEncomiendas;
    private static EncomiendasDAO eDAO = new EncomiendasDAO();
    private static Object[][] dtEncomienda;
    private static JComboBox cmbRemitente;
    private static JComboBox cmbDestinatario;
    
    
    /**
     * Launch the application.
     */
    public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            UsuarioDAO uDAO = new UsuarioDAO(); 
            try {
                cmbRemitente = new JComboBox();
                cmbDestinatario = new JComboBox();
                ListarEncomiendasAdmin frame = new ListarEncomiendasAdmin();
                frame.setVisible(true);
                Actualizar_Tabla();
                cmbRemitente = uDAO.usuarios_combo();
                cmbDestinatario = uDAO.usuarios_combo();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });

CONNECTION CODE

public class ConexionBD {
    
    /* Datos para la conexion */
    private String bd = "proy_encomiendas";//Base de datos
    private String user = "root"; //Usuario
    private String password = ""; //Contraseña
    private String host = "jdbc:mysql://localhost/"+bd; //Servidor + Base de datos
    public static Connection conn = null; //Inicializamos con valor null la conexion
    
    /* Constructor de la clase que se conecta a la Base de Datos */
    public ConexionBD(){
        try{
            //Driver para MySQL
            Class.forName("com.mysql.jdbc.Driver");
            
            //Obtenemos la conexión
            conn = DriverManager.getConnection(host,user,password);
            if (conn!=null){
                System.out.println("Se conecto a la base de datos "+bd+"");
            }
        }catch(SQLException e){
            System.out.println("Error en la ejecución:" + e.getErrorCode() + " " + e.getMessage());
        }catch(ClassNotFoundException e){
            System.out.println(e);
        }
    }

    public Connection getConexion(){
        return ConexionBD.conn;
    }

I debugged the application and as it turns out, it's fetching the data from the database (I can see the iterations with the different numbers it should be loading into the combo boxes), but in the end when the frame displays, both combo boxes are empty and I get a SQLNonTransient Exception.

So, any help you can offer would be appreciated. Thanks in advance.

edit: connection is via JDBC I'm using wampserver which includes MYSQL.

Community
  • 1
  • 1
  • As you see in the stacktrace, the connection is closed before the statement gets executed. Could you add your connection-code? – ItFreak Sep 04 '18 at 15:10
  • maybe this will help you: https://stackoverflow.com/questions/6172930/sqlnontransientconnectionexception-no-current-connection-in-my-application-whi – ItFreak Sep 04 '18 at 15:12
  • @ItFreak added the connection code there. – Jose Ignacio Radesca Sep 04 '18 at 15:53
  • It seems like the class ConexionBD is not instanciated (created with new keyword). You call this.getCeonnexion, so I think there is never a connection created to the database – ItFreak Sep 05 '18 at 06:45

1 Answers1

0

change your ConexionBD class code as below load Driver in static block, create new db connection every time you call getConexion method.

static {
    try{
        //Driver para MySQL
        Class.forName("com.mysql.jdbc.Driver");
    } catch(ClassNotFoundException e){
        System.out.println(e);
    }
 }

 public ConexionBD() {
 }

  public Connection getConexion(){
    Connection conn = null;
    try {
         conn = DriverManager.getConnection(host,user,password);
         if (conn!=null){
            System.out.println("Se conecto a la base de datos "+bd+"");
         }
    } catch(SQLException e){
        System.out.println("Error en la ejecución:" + e.getErrorCode() + " " + e.getMessage());
    }
    return conn; 
  }