Create Pie Chart using database values


 

Create Pie Chart using database values

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

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

Create Pie Chart using database values

Java provides JFreeChart library which helps in creating a number of charts.It provides several classes and methods which enables the programmer to create charts very easily. You have already learned bar charts, line charts in the previous sections. Here we are going to create a pie chart by retrieving the values from the database.

Here is the code:

import java.sql.*;
import java.io.*;
import org.jfree.ui.*;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.data.*;
import org.jfree.data.jdbc.JDBCPieDataset;

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

		String query = "SELECT * from chart";
		JDBCPieDataset dataset = new JDBCPieDataset(
				"jdbc:mysql://localhost:3306/test", "com.mysql.jdbc.Driver",
				"root", "root");

		dataset.executeQuery(query);
		JFreeChart chart = ChartFactory.createPieChart("Test", dataset, true,
				true, false);
		ChartPanel chartPanel = new ChartPanel(chart);
		chartPanel.setPreferredSize(new java.awt.Dimension(500, 270));
		ApplicationFrame f = new ApplicationFrame("Chart");
		f.setContentPane(chartPanel);
		f.pack();
		f.setVisible(true);

	}
}

Output:

Ads