In this section we will explains how you can read simple data from a database table and then use JFreeChart to create a chart of your choice.
Business Data
Consider we have the following MySQL table mobile_tbl(mobile_brand VARCHAR(100) NOT NULL, unit_sale INT NO NULL);
Consider this table is having the following records −
Mobile Brands | Unit Sales |
---|---|
IPhone5S | 20 |
Samsung Grand | 20 |
MotoG | 40 |
Nokia Lumia | 10 |
Chart Generation Using Database
Following is the code to create a Pie Chart based on the information provided in mobile_tbl table available in test_db in a MySQL database. Based on your requirements, you can use any other database.
import java.io.*; import java.sql.*; import org.jfree.chart.ChartUtilities; import org.jfree.chart.ChartFactory; import org.jfree.chart.JFreeChart; import org.jfree.data.general.DefaultPieDataset; public class PieChart_DB { public static void main( String[ ] args )throws Exception { String mobilebrands[] = { "IPhone 5s", "SamSung Grand", "MotoG", "Nokia Lumia" }; /* Create MySQL Database Connection */ Class.forName( "com.mysql.jdbc.Driver" ); Connection connect = DriverManager.getConnection( "jdbc:mysql://localhost:3306/jf_testdb" , "root", "root123"); Statement statement = connect.createStatement( ); ResultSet resultSet = statement.executeQuery("select * from mobile_data" ); DefaultPieDataset dataset = new DefaultPieDataset( ); while( resultSet.next( ) ) { dataset.setValue( resultSet.getString( "mobile_brand" ) , Double.parseDouble( resultSet.getString( "unit_sale" ))); } JFreeChart chart = ChartFactory.createPieChart( "Mobile Sales", // chart title dataset, // data true, // include legend true, false ); int width = 560; /* Width of the image */ int height = 370; /* Height of the image */ File pieChart = new File( "Pie_Chart.jpeg" ); ChartUtilities.saveChartAsJPEG( pieChart , chart , width , height ); } }
Let us keep the above Java code in PieChart_DB.java file, and then compile and run it from the command prompted as −
$javac PieChart_DB.java $java PieChart_DB
If everything is fine, it will compile and run to create a JPEG image file named Pie_Chart.jpeg having the following chart.