Problem with ResultSet in Java / MySQL

1

Very good, companions.

I am having a certain problem that I still can not identify well in Java with a ResultSet that I use, it throws me an error of java.sql.SQLException: Operation not allowed after ResultSet closed and I still can not identify why.

My code is very simple, I only generate a flat file with data coming from a Database which are delimited by "|", but, when filling the file with the data through a ResultSet this indicates me this error and does not perform the function. Here I add the code that I have used for this application:

Event code of the create file button

    ModelCartas_Laborales obj = new ModelCartas_Laborales();
    ControllerCartas_Laborales obj2 = new ControllerCartas_Laborales();
    ControllerEscribir archivo = new ControllerEscribir();
    obj.setLapso(jTextField1.getText());
    try {
        archivo.crearArchivo(obj2.obtenerCartas(obj));
    } catch (SQLException ex) {
        Logger.getLogger(CLFormulario.class.getName()).log(Level.SEVERE, null, ex);
    }

Control class code

public class ControllerCartas_Laborales {
Conexion con = new Conexion();
String sql;

public ResultSet obtenerCartas(ModelCartas_Laborales obj){
    ResultSet rs;
    sql = "SELECT DISTINCT 'NULL' AS ID, 'CC' AS COD_DOC, tr.CODIGO AS EMPLEADO, ct.CODIGO AS CONTRATO, ct.ID_EMP AS EMPRESA,\n" +
    "   tr.'DESCRIPCION' AS  NOMBRE_EMPLEADO, npn.'DESCRIPCION_CARGO' AS CARGO, IF(ct.'FECHA_CONT_HA' = '99999999', 'INDEFINIDO', 'FIJO') AS TIPO_CONTRATO,\n " +
    "   ct.'FECHA_INGRESO' AS FECHA_INGRESO_CONTRATO, ct.'FECHA_CONT_HA' AS FECHA_CONTRATO_HASTA, CAST(ct.'SALARIO' AS UNSIGNED) AS SALARIO_CONTRATO, 'NULL' AS FECHA_CREACION_EMPLEADO,\n" +
    "   ct.'FECHA_RETIRO' AS FECHA_RETIRO, IF(sus.NOMBRES = tr.DESCRIPCION, 'SUSTITUCION', 'NORMAL') AS SUSTITUCION, IF(sus.FECHA_INGRESO = (NULL), ' ', sus.FECHA_INGRESO) AS FECHA_INGRESO_INSTITUCIONAL,\n" +
    "   (SELECT CAST(SUM(sal.'NMMOV_VALOR') AS UNSIGNED) FROM NMRESUMEN_PAGOS_NOMINA sal WHERE sal.ID_TERC = npn.'ID_TERC' AND sal.ID_CPTO = '001' AND sal.LAPSO_DOC = npn.'LAPSO_DOC') AS SALARIO,\n " +
    "   (SELECT CAST(SUM(sal.'NMMOV_VALOR') AS UNSIGNED) FROM NMRESUMEN_PAGOS_NOMINA sal WHERE sal.ID_TERC = npn.'ID_TERC' AND sal.ID_CPTO IN ('002','003','004','008','009','010','011') AND sal.LAPSO_DOC = npn.'LAPSO_DOC') AS HORAS_EXTRA \n" +
    "   FROM NMRESUMEN_PAGOS_NOMINA npn \n" +
    "   INNER JOIN TERCEROS tr \n" +
    "   ON tr.'CODIGO' = npn.'ID_TERC' \n" +
    "   INNER JOIN CONTRATOS ct \n" +
    "   ON ct.'ID_TERC' = tr.'CODIGO' \n" +
    "   LEFT JOIN SUSTITUCION_ANTIGUOS sus \n" +
    "   ON sus.'NOMBRES' = tr.'DESCRIPCION' \n" +
    "   INNER JOIN CONCEPTOS_NOMINA cn \n" +
    "   ON cn.CODIGO = npn.ID_CPTO \n" +
    "   WHERE \n" +
    "   npn.'LAPSO_DOC' ='"+obj.getLapso()+"' \n"+
    "   GROUP BY \n" +
    "   NOMBRE_EMPLEADO \n";
    rs = con.consultar(sql);
    return rs;
}

}

Code of the class that will generate the flat file

public class ControllerEscribir {
Calendar calendario = new GregorianCalendar();
String d = String.valueOf(calendario.get(Calendar.DAY_OF_MONTH));
String M = String.valueOf(calendario.get(Calendar.MONTH));
String y = String.valueOf(calendario.get(Calendar.YEAR));
String s = String.valueOf(calendario.get(Calendar.SECOND));
String m = String.valueOf(calendario.get(Calendar.MINUTE));
String H = String.valueOf(calendario.get(Calendar.HOUR));
String nombreArchivo = "CertificadosLaborales_"+y+M+d+"_"+H+m+s+".txt";
String datos;

public void crearArchivo(ResultSet rs) throws SQLException{
    File f;
    f = new File(nombreArchivo);
    ResultSet rs2 = rs;
    try {
        FileWriter w = new FileWriter(f);
        BufferedWriter bw = new BufferedWriter(w);
        PrintWriter salidaTexto = new PrintWriter(bw);
        while(rs2.next()){
            salidaTexto.write(rs2.getString("ID")+"|"+rs2.getString("COD_DOC")+"|"+
            rs2.getString("EMPLEADO")+"|"+rs2.getString("CONTRATO")+"|"+
            rs2.getString("EMPRESA")+"|"+rs2.getString("NOMBRE_EMPLEADO")+"|"+
            rs2.getString("CARGO")+"|"+rs2.getString("TIPO_CONTRATO")+"|"+
            rs2.getString("FECHA_INGRESO_CONTRATO")+"|"+rs2.getString("FECHA_CONTRATO_HASTA")+"|"+
            rs2.getString("SALARIO_CONTRATO")+"|"+rs2.getString("FECHA_CREACION_EMPLEADO")+"|"+
            rs2.getString("FECHA_RETIRO")+"|"+rs2.getString("SUSTITUCION")+"|"+rs2.getString("FECHA_INGRESO_INSTITUCIONAL")+"|"+
            rs2.getString("SALARIO")+"|"+rs2.getString("HORAS_EXTRA")+"\n");
        }

        salidaTexto.close();
        bw.close();
    }catch (IOException ex) {
        Logger.getLogger(ControllerEscribir.class.getName()).log(Level.SEVERE, null, ex);
    }
}

}

Code class connection

public class Conexion implements Configuracion{
    private static Connection con = null;

static {
    try {
        Class.forName(DRIVER);
        con = (Connection) DriverManager.getConnection(CONNECTION_URL, USERNAME, PASSWORD);
        if (con != null) {
            System.out.println("Conexion exitosa ");
        } else {
            System.out.println("Conexion fallida");
        }
    } catch (ClassNotFoundException | SQLException e) {
        e.printStackTrace();
    }
}

public static Connection getConnection() {
    return con;
}

public boolean ejecutar(String sql) {
    try {
        Statement sentencia;
        sentencia = getConnection().createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
        sentencia.executeUpdate(sql);
        sentencia.close();
    } catch (SQLException e) {
        e.printStackTrace();
        return false;
    }
    return true;
}

public ResultSet consultar(String sql) {
    ResultSet resultado = null;
    try {
        Statement sentencia;
        sentencia = getConnection().createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
        resultado = sentencia.executeQuery(sql);       
        sentencia.close();
    } catch (SQLException e) {
        e.printStackTrace();
        return null;
    }
    return resultado;
}

}

When I start running the program and give it the determined time, it throws me the error which indicates these lines:

I do not know if I'm skipping a step or I'm doing one more ... I would greatly appreciate your help in solving this dilemma.

    
asked by Salth95 06.06.2017 в 19:01
source

1 answer

0
public ResultSet consultar(String sql) {
    ResultSet resultado = null;
    try {
        Statement sentencia;
        sentencia = getConnection().createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
        resultado = sentencia.executeQuery(sql);       
        sentencia.close();//Aqui estas cerrando el statement
    } catch (SQLException e) {
        e.printStackTrace();
        return null;
    }
    return resultado;
}

In the code that I put above you close the statement, therefore the ResultSet that you created with that statement also closes. Therefore when you want to use it throws the exception because it is already closed:

public ResultSet obtenerCartas(ModelCartas_Laborales obj){
    ResultSet rs;
    sql = "SELECT ...";
    rs = con.consultar(sql);//Aqui llega cerrado
    return rs;
}
    
answered by 06.06.2017 / 20:06
source