JFreeChart JDBC Pie Chart -Java Example

This tutorial explains how to create a Pie chart over a JDBC connection using the JFreeChart Java API. If you have a requirement to read a database table and create a Pie Chart out of the resulting rows in the table, then you have landed at the right spot. The table with which we are going to create a Pie Chart sits in a Oracle database. You can also extend this tutorial to support any other database by simply using the right driver files.We will begin this tutorial by creating a table in Oracle and populate the data required for the pie chart:

Prepare Pie Chart Data

The table we want to use for our pie chart datasource, has five rows each with a state and a count value against it. The SQL scripts to create the table and populate the data is provided below: [ Note: We have randomized the data using DBMS_RANDOM package ]
create table pie_chart_Data
(
State varchar2(20),
success_rate number
)

insert into pie_chart_Data values ('S1',1)
insert into pie_chart_Data values ('S2',1)
insert into pie_chart_Data valuesd ('S3',1)
insert into pie_chart_Data values ('S4',1)
insert into pie_chart_Data values ('S5',1)

update pie_chart_data set success_rate=TRUNC(DBMS_RANDOM.value(70,99))

At the end of this step, we have setup a data source for our Pie chart. We are now ready to to download the JAR files required for this tutorial.

Download JAR files - JFreeChart

You need the following JAR files for this tutorial: jfreechart-1.0.14.jar, ojdbc6.jar and jcommon-1.0.17.jar. You may still be able to create the Pie Chart if you don't have the right versions. As always, you can post a comment if you get any exceptions in this process.

JDBC Pie Chart Example - JFreeChart Java Program

We have created the data source and have the required JAR files. We now provide the fully working Java code that reads this data source and creates a Pie Chart. This tutorial is exactly on the same lines as of creating bar chart over JDBC in JFreeChart. The complete program is provided below:
import java.sql.*; 
import java.io.*;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.chart.ChartFactory; 
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.JFreeChart; 
import org.jfree.chart.ChartUtilities; 
import org.jfree.data.xml.DatasetReader;
import java.io.InputStream;
public class PieChartJDBCExample {  
        
        public static void main(String[] args) throws Exception{
                
                Class.forName ("oracle.jdbc.OracleDriver"); 
                Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@//localhost:1521/xe", "hr", "hr");
                DefaultPieDataset my_pie_chart_dataset = new DefaultPieDataset();
                Statement stmt = conn.createStatement();
                /* Populate data from table to JFreeChart */
                try {
                        ResultSet query_set = stmt.executeQuery("select state,success_Rate from pie_chart_Data");
                        while (query_set.next()) {
                                String state = query_set.getString("STATE");
                                int success_rate = query_set.getInt("SUCCESS_RATE");
                                my_pie_chart_dataset.setValue(state, success_rate); //Convert data source from table to Pie Chart Data Source                               
                                }
                /* Create Logical Chart */
                JFreeChart PieChartObject=ChartFactory.createPieChart("State Vs Success Rate - Pie Chart Example",my_pie_chart_dataset,true,true,false);
                /* Close JDBC specific objects */
                query_set.close();
                stmt.close(); 
                conn.close();
                /* Specify dimensions and quality factor for Pie Chart */
                int width=640; 
                int height=480;   
                float quality=1; /* Quality factor */
                /* Write Pie Chart as a JPEG file */
                File BarChart=new File("SQL2PieChart.png");              
                ChartUtilities.saveChartAsJPEG(BarChart, quality, PieChartObject,width,height); 
                }
                 catch (Exception i)
                 {
                         System.out.println(i);
                 }
                }               
        }

        
The code creates the Pie chart for the SQL table. Note that we have used DefaultPieDataset object to capture data for Pie Chart. The data source input is added using the "setValue" method.

Output Example

The output generated by the above code is a Pie Chart in JPEG format. The chart is provided below for our test data:

Java JFreeChart JDBC Pie Chart Example
Java JFreeChart JDBC Pie Chart Example

Exceptions - Troubleshooting Guide


You can easily solve some of the common exceptions (at runtime) you get when running this example, by making sure you have the JAR files in the right path. Some of the exceptions and the reasons are documented below:

Exception in thread "main" java.lang.ClassNotFoundException: oracle.jdbc.OracleDriver

        at java.net.URLClassLoader$1.run(Unknown Source)
        at java.net.URLClassLoader$1.run(Unknown Source)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at java.lang.Class.forName0(Native Method)
        at java.lang.Class.forName(Unknown Source)
        at PieChartJDBCExample.main(PieChartJDBCExample.java:14)

The above exception occurs when you are missing ojdbc6.jar file in your CLASSPATH. Adding this JAR file would solve the problem. The below exception occurs when you are missing jcommon-1.0.17.jar in your CLASSPATH. Again, adding this file to the path would fix the exception for you.

Exception in thread "main" java.lang.NoClassDefFoundError: org/jfree/util/Public Cloneable
        at java.lang.ClassLoader.defineClass1(Native Method)
        at java.lang.ClassLoader.defineClass(Unknown Source)
        at java.security.SecureClassLoader.defineClass(Unknown Source)
        at java.net.URLClassLoader.defineClass(Unknown Source)
        at java.net.URLClassLoader.access$100(Unknown Source)
        at java.net.URLClassLoader$1.run(Unknown Source)
        at java.net.URLClassLoader$1.run(Unknown Source)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at PieChartJDBCExample.main(PieChartJDBCExample.java:16)
Caused by: java.lang.ClassNotFoundException: org.jfree.util.PublicCloneable
        at java.net.URLClassLoader$1.run(Unknown Source)
        at java.net.URLClassLoader$1.run(Unknown Source)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        ... 13 more
If you are missing JFreeChart JAR file in your CLASSPATH, you will get the following exception at runtime.
Exception in thread "main" java.lang.NoClassDefFoundError: org/jfree/data/general/PieDataset
        at java.lang.Class.getDeclaredMethods0(Native Method)
        at java.lang.Class.privateGetDeclaredMethods(Unknown Source)
        at java.lang.Class.getMethod0(Unknown Source)
        at java.lang.Class.getMethod(Unknown Source)
        at sun.launcher.LauncherHelper.getMainMethod(Unknown Source)
        at sun.launcher.LauncherHelper.checkAndLoadMain(Unknown Source)
Caused by: java.lang.ClassNotFoundException: org.jfree.data.general.PieDataset
        at java.net.URLClassLoader$1.run(Unknown Source)
        at java.net.URLClassLoader$1.run(Unknown Source)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        ... 6 more

Putting the right JAR files solves most of the common issues you encounter while creating this pie chart.

JFreeChart - JDBC Pie Chart - Summary


That completes our tutorial that explained how to create a Pie Chart from a Oracle table over JDBC connection, using the JFreeChart Java API library. If you run into any other issues, you can post this in the comments section of the blog. We will have a look. Subscribe to your blog and never miss a tutorial.

No comments:

Post a Comment