Share on Google+Share on Google+

Create Bar Chart with database values

Advertisement
In this section, you will learn how to create a bar chart by retrieving the values from the database.

Create Bar Chart with database values

In this section, you will learn how to create a bar chart by retrieving the values from the database. For this purpose, we have used JFreechart api. The class JDBCCategoryDataset of this api provides the implementation over a database JDBC result set. Its constructor consists of url, driver, user, pass to connect to the database. The method executeQuery( query) executes the query against the existing database connection. The method createBarChart3D() of the class ChartFactory creates a vertical 3D bar chart. Now with the use of saveChartAsJPEG() method of ChartUtilities class, we have saved the chart to a file specified in JPEG format. If you want to save the file in PNG format, you have to use saveChartAsPNG() method.

Here is the code:

import java.sql.*;
import java.io.*;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.*;
import org.jfree.data.jdbc.JDBCCategoryDataset;

public class Chart {
	public static void main(String[] args) throws Exception {

	       String query = "SELECT * from chart";
	       JDBCCategoryDataset dataset = new JDBCCategoryDataset(
		"jdbc:mysql://localhost:3306/test", 
                "com.mysql.jdbc.Driver","root", "root");
	       dataset.executeQuery(query);
	       JFreeChart chart =  
                ChartFactory.createBarChart3D("Test", "Id", "Score",
	        dataset, PlotOrientation.VERTICAL, true, true, false);
	       try {
	       ChartUtilities.saveChartAsJPEG(new File("C:/chart.jpg"),
                chart,400, 300);
	       } catch (IOException e) {
	       System.out.println("Problem in creating chart.");
  }
	}
}

Output

Advertisements

Posted on: November 28, 2009 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.