- JFreeChart 教程
- JFreeChart - 主页
- JFreeChart - 概述
- JFreeChart - 安装
- JFreeChart - 架构
- JFreeChart - 引用的 API
- JFreeChart - 饼图
- JFreeChart - 条形图
- JFreeChart - 折线图
- JFreeChart - XY 图表
- JFreeChart - 3D 图表/条形图
- JFreeChart-气泡图
- JFreeChart - 时间序列图表
- JFreeChart - 文件接口
- JFreeChart - 数据库接口
- JFreeChart 有用资源
- JFreeChart - 快速指南
- JFreeChart - 有用的资源
- JFreeChart - 讨论
JFreeChart - 数据库接口
本章介绍如何从数据库表中读取简单数据,然后使用 JFreeChart 创建您选择的图表。
业务数据
假设我们有以下 MySQL 表 mobile_tbl(mobile_brand VARCHAR(100) NOT NULL, unit_sale INT NO NULL);
考虑该表具有以下记录 -
| 手机品牌 | 销量 |
|---|---|
| IPhone 5S | 20 |
| 三星大酒店 | 20 |
| 摩托G | 40 |
| 诺基亚Lumia | 10 |
使用数据库生成图表
以下是根据 MySQL 数据库中 test_db 中的 mobile_tbl 表中提供的信息创建饼图的代码。根据您的要求,您可以使用任何其他数据库。
import java.io.*;
import java.sql.*;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.data.general.DefaultPieDataset;
public class PieChart_DB {
public static void main( String[ ] args )throws Exception {
String mobilebrands[] = {
"IPhone 5s",
"SamSung Grand",
"MotoG",
"Nokia Lumia"
};
/* Create MySQL Database Connection */
Class.forName( "com.mysql.jdbc.Driver" );
Connection connect = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/jf_testdb" ,
"root",
"root123");
Statement statement = connect.createStatement( );
ResultSet resultSet = statement.executeQuery("select * from mobile_data" );
DefaultPieDataset dataset = new DefaultPieDataset( );
while( resultSet.next( ) ) {
dataset.setValue(
resultSet.getString( "mobile_brand" ) ,
Double.parseDouble( resultSet.getString( "unit_sale" )));
}
JFreeChart chart = ChartFactory.createPieChart(
"Mobile Sales", // chart title
dataset, // data
true, // include legend
true,
false );
int width = 560; /* Width of the image */
int height = 370; /* Height of the image */
File pieChart = new File( "Pie_Chart.jpeg" );
ChartUtilities.saveChartAsJPEG( pieChart , chart , width , height );
}
}
让我们将上述 Java 代码保留在PieChart_DB.java文件中,然后根据提示的命令编译并运行它:
$javac PieChart_DB.java $java PieChart_DB
如果一切正常,它将编译并运行以创建一个名为Pie_Chart.jpeg的 JPEG 图像文件,其中包含以下图表。
