sql >> Base de Datos >  >> RDS >> Sqlserver

El documento no tiene páginas. Informe de jaspe

En primer lugar, la gestión de recursos...

Solo debe abrir una única conexión a la base de datos si puede. Asegúrese de cerrarlo antes de que se cierre la aplicación. El proceso de conexión puede ser costoso, por lo que solo querrás hacerlo cuando sea absolutamente necesario...

Cierras tus recursos una vez que hayas terminado con ellos. Esto se logra mejor usando un try-finally bloquear...

private Connection con;

protected void close() throws SQLException {
    if (con != null) {
        con.close();
    }
}

protected Connection getConnection() throws ClassNotFoundException, SQLException {
    if (con == null) {
        Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
        String url = "jdbc:odbc:*****";
        String user = "******";
        String pass = "******";
        Connection con = DriverManager.getConnection(url, user, pass);
    }
    return con;
}

private void search() throws Exception {

    Statement state = null;
    ResultSet rs = null;

    try {

        state = getConnection().createStatement();

        rs = state.executeQuery("SELECT "
                + "pIDNo AS 'Patient ID',"
                + "pLName AS 'Last Name',"
                + "pFName AS 'First Name',"
                + "pMI AS 'M.I.',"
                + "pSex AS 'Sex',"
                + "pStatus AS 'Status',"
                + "pTelNo AS 'Contact No.',"
                + "pDocID AS 'Doctor ID',"
                + "pAddr AS 'St. No.',"
                + "pStreet AS 'St. Name',"
                + "pBarangay AS 'Barangay',"
                + "pCity AS 'City',"
                + " pProvince AS 'Province',"
                + " pLNameKIN AS 'Last Name',"
                + "pFNameKIN AS 'First Name',"
                + "pMIKIN AS 'M.I.',"
                + "pRelationKIN AS 'Relation',"
                + "pTotalDue AS 'Total Due'"
                + " FROM dbo.Patients");
        ResultSetMetaData rsmetadata = rs.getMetaData();
        int columns = rsmetadata.getColumnCount();

        DefaultTableModel dtm = new DefaultTableModel();
        Vector column_name = new Vector();
        Vector data_rows = new Vector();

        for (int i = 1; i < columns; i++) {
            column_name.addElement(rsmetadata.getColumnName(i));
        }
        dtm.setColumnIdentifiers(column_name);

        while (rs.next()) {
            data_rows = new Vector();
            for (int j = 1; j < columns; j++) {
                data_rows.addElement(rs.getString(j));
            }
            dtm.addRow(data_rows);
        }
        tblPatient.setModel(dtm);

    } finally {
        try {
            rs.close();
        } catch (Exception e) {
        }
        try {
            state.close();
        } catch (Exception e) {
        }
    }
}

Ahora al problema en cuestión...

Parece que ha creado dos referencias a con . Uno como campo de clase y otro como variable de método (en search ).

Entonces estás pasando con a Jasper Reports, que sospecho que es null . En su lugar, debe usar getConnection() como se describe anteriormente.

public void reportviewer() {
    try{
        String report = "C:\\Users\\cleanfuel\\Documents\\NetBeansProjects\\StringManipulation\\src\\stringmanipulation\\report1.jrxml";
        JasperReport jasp_report = JasperCompileManager.compileReport(report);
        JasperPrint jasp_print = JasperFillManager.fillReport(jasp_report, null, getConnection());
        JasperViewer.viewReport(jasp_print);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Actualizado con trabajador en segundo plano...

Un informe puede tardar algún tiempo en compilarse y completarse. Debe descargar este trabajo a un subproceso en segundo plano para que no interfiera con su interfaz de usuario (o haga que parezca que su aplicación está bloqueada).

La solución más simple sería usar un SwingWorker . Tiene funcionalidad para resincronizar los hilos con la interfaz de usuario

public void reportviewer() {
    // Disable any UI components you don't want the user using while
    // the report generates...
    new ReportWorker().execute();
}

public class ReportWorker extends SwingWorker<JasperPrint, Void> {

    @Override
    protected JasperPrint doInBackground() throws Exception {
        String report = "C:\\Users\\cleanfuel\\Documents\\NetBeansProjects\\StringManipulation\\src\\stringmanipulation\\report1.jrxml";
        JasperReport jasp_report = JasperCompileManager.compileReport(report);
        JasperPrint jasp_print = JasperFillManager.fillReport(jasp_report, null, getConnection());
        return jasp_print;
    }

    @Override
    protected void done() {
        try {
            JasperPrint jasp_print = get();
            JasperViewer.viewReport(jasp_print);
        } catch (Exception exp) {
            exp.printStackTrace();
        }
        // Renable any UI components you disabled before the report run
    }
}

Eche un vistazo a Concurrencia en Swing para más detalles.

Consejos

Si puede compilar previamente el informe y cargarlo (en lugar de cargar el XML), hará que el proceso del informe sea más rápido.