Create Charts in Java using Database

In addition to specifying the chart data (or the URL for the file in which the chart data is stored) directly in the JSON/XML code, you can also fetch data for the chart from a database.

This section showcases how you can do this using the FusionCharts JSP wrapper.

Before you proceed, make sure you have installed and set up the plugin correctly. Although you can create all kinds of charts using this method, in this section we will focus on only these two examples.

Creating a Column 2D Chart

Assume that you have a fusioncharts_jspsample database with the Country table that stores the population of all countries in the world. Using the data in this database, let's say you want to plot a column 2D chart showing the top ten most populous countries in the world.

You can download this database from the MYSQL website or refer to the sample database available here .

The resultant column 2D chart looks like this:

FusionCharts will load here..

The data structure to create this chart, by fetching chart data from a database, is given below:


<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page import="java.sql.*" %>
<%@page import="java.util.*" %>
<%@page import="*" %>


    The following 4 code lines contain the database connection information.
    Alternatively, you can move these code lines to a separate file and
    include the file here. You can also modify this code based on your 
    database connection. 

   String hostdb = "localhost:3306";              // MySQl host
   String userdb = "root";                      // MySQL username
   String passdb = "";                          // MySQL password
   String namedb = "fusioncharts_jspsample";      // MySQL database name

    // Establish a connection to the database
    DriverManager.registerDriver(new com.mysql.jdbc.Driver());
    Connection con = DriverManager.getConnection("jdbc:mysql://" + hostdb + "/" + namedb , userdb , passdb);


<!DOCTYPE html>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Creating Charts with Data from a Database -</title>
<!--     Step 1: Include the `fusioncharts.js` file. This file is needed to
        render the chart. Ensure that the path to this JS file is correct.
        Otherwise, it may lead to JavaScript errors.
        <script src="../scripts/fusioncharts.js"></script>
         <div id="chart"></div>
<!--    Step 2: Include the `` file as a package in your 

        Step 3:Include the package in the file where you want to show 

        <%@page import="fusioncharts.FusionCharts" %>


        Step 4: Create a chart object using the FusionCharts JAVA class 
        constructor. Syntax for the constructor: 
        `FusionCharts("type of chart", "unique chart id", "width of chart",
                        "height of chart", "div id to render the chart", 
                        "data format", "data source")`   

            Gson is a Java library facilitating conversion of Java objects 
            into their JSON representation and 
            JSON strings into their equivalant Java objects. 
            Gson can also work with arbitrary Java objects 
            including the pre-existing ones that 
            you may not have the source-code for. 
            Read the note below this code for more details on the google-gson library.    

            Gson gson = new Gson();

            // Form the SQL query that returns the top 10 most populous countries
            String sql="SELECT Name, Population FROM Country ORDER BY Population DESC LIMIT 10";

            // Execute the query
            PreparedStatement pt=con.prepareStatement(sql);    
            ResultSet rs=pt.executeQuery();

            // The 'chartobj' map object holds the chart attributes and data.
            Map<String, String> chartobj = new HashMap<String, String>();

            chartobj.put("caption", "Top 10 most populous countries");
            chartobj.put("showValues", "0");
            chartobj.put("theme", "zune");

            // Push the data into the array using map object.
            ArrayList arrData = new ArrayList();
            while( {
                Map<String, String> lv = new HashMap<String, String>();
                lv.put("label", rs.getString("Name"));
                lv.put("value", rs.getString("Population"));

            //close the connection.

            //create 'dataMap' map object to make a complete FC datasource.
             Map<String, String> dataMap = new LinkedHashMap<String, String>();  
            gson.toJson() the data to retrieve the string containing the
            JSON representation of the data in the array.
             dataMap.put("chart", gson.toJson(chartobj));
             dataMap.put("data", gson.toJson(arrData));

            FusionCharts columnChart= new FusionCharts(
                        //type of chart
                        //unique chart ID
                        //width and height of the chart
                        //div ID of the chart container
                        //data format
                        //data source


<!--    Step 5: Render the chart    -->                


The code above uses the google-gson library.
Gson is a Java library that can be used to convert:
- Java objects into their corresponding JSON representation
- JSON strings into their corresponding Java objects.
Gson allows working with arbitrary Java objects that include pre-existing objects for which you may not have the source code.

The google-gsn library :
- Provides the toJson() and fromJson() methods for converting Java objects to JSON and the other way round
- Allows conversion of the already existing unmodifiable objects to and from JSON
- Supports Java Generics extensively
- Allows custom representations of objects
- Supports arbitrarily complex objects (with deep inheritance hierarchies and extensive use of generic types)

The code above imports the package that enables the conversion from JSON to Java and Java to JSON.

Click here for more information on google-gson.

Was this article helpful to you ?