Google

Tuesday, July 21, 2009

MySQL: How to create .jasper and read them from within Netbeans

Download iReports plugin for Netbeans. I'm using Netbeans 6.5

Then, unzip the zipped plugin. You should have 4 .nbm files
after unzipping:







Install each plugin into Netbeans:




Create a new report from within Netbeans:




When you click Preview Report, the .jrxml file is
compiled into a .jasper file. See red-circled above.

Then write code to load and display the .jasper file:



Text Version of code:

private void miReportJasperExtensionActionPerformed(java.awt.event.ActionEvent evt) {
runReportJasperExtension("src/myreport/report1.jasper");
}


private void runReportJasperExtension(String reportFile) {
try{
Class.forName(JDBC_DRIVER).newInstance();
connection = DriverManager.getConnection(DATABASE_URL, "loginname", "passwd");
String jasperPrint = JasperFillManager.fillReportToFile(reportFile,null,connection);
JasperViewer.viewReport(jasperPrint,false,true);

}catch(Exception ex) {
String connectMsg = "Could not view " + ex.getMessage() + " " + ex.getLocalizedMessage();
System.out.println(connectMsg);
}finally {
try {
statement.close();
} catch (Exception e) {
}
}
}

Note that miReportJasperExtension is my JMenuItem, you
can use a JButton instead.

You also need these variables:

private Connection connection;
private String JDBC_DRIVER = "com.mysql.jdbc.Driver";
private String DATABASE_URL = "jdbc:mysql://localhost/icomis";



Run your program and the JasperViewer will show the report:




Everything is done from within Netbeans. You do not need
to use the standalone iReport tool.