首页 / 网页编程 / JSP / 在JSP页面中轻松实现数据饼图
在JSP页面中轻松实现数据饼图2008-03-10sadyJSP提供了很多简单实用的工具,其中包括从数据库中读出数据,发送数据,并能够把结果显示在一个饼状图形。现在让我们看看这一简单而实用的方法。你所需要的东西为了能正确运行这一文章相关的范例,你必须需要JDK 1.2或更高的版本、一个关系数据库管理系统、一个JSP网络服务器。我都是在Tomcat调试这些例子,同时我也使用了Sun Java 2 SDK发布的com.sun.image.codec.jpegclasses。数据库设计假设你在一家从事销售新鲜水果的公司上班,公司出售的水果包括:苹果、桔子、葡萄。现在你的老板想用一个饼状图形显示每一种水果的总出售量,饼状图形能使每一种产品的销售情况一目了然,老板可以迅速掌握公司的产品成交情况。表A使用了本文中的两种数据库列表。第一种列表(Products)包含所有销售产品的名称;第二种列表(Sales)包含每一种产品对应的销售量。Listing ADatabase Design---------------p_products table----------------productID int (number) not nullproductname String (varchar) not nullp_sales table-------------saleID int (number) not nullproductID int (number) not nullamount float not null产品(Products)列表包含productID和productname两个域。销售(Sales)列表包含saleID, productID,以及总额。销售列表中的productID提供了这两个列表之间的关联。销售列表中的总额包含了每一次出售的现金数额,这些数额以浮点型数据出现。表B中的getProducts()方法连接了两个数据库,并把所有的产品名称保存在数组中:Listing B////////////////////////////////////////////////////////////
//Get products from the database as a String array
////////////////////////////////////////////////////////////
public String[] getProducts()
{
String[] arr = new String[0];
Connection con;
Statement stmt;
ResultSet rs;
int count = 0;
String sql = "select * from p_products order by productID";
try
{
//Load Driver: Class.forName(driver);
//Connect to the database with the url
con = DriverManager.getConnection(dburl , dbuid , dbpwd);
stmt = con.createStatement();
//Get ResultSet
rs = stmt.executeQuery(sql);
//Count the records
while(rs.next())
{count++;}
//Create an array of the correct size
arr = new String[count];
//Get ResultSet (the portable way of using rs a second time)
rs = stmt.executeQuery(sql);
while(rs.next())
{
arr[rs.getInt("productID")] = rs.getString("productname");
}
stmt.close();
con.close();
}
catch (java.lang.Exception ex)
{
arr[0] = ex.toString();
}
return arr;
}