Create Bar Chart with database values


 

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.

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

In this example we are reading the data from MySQL database and then using the jfree chart library to create chart. You can see the above image which is created from the program.

Ads