AutoCAD 3DMAX C语言 Pro/E UG JAVA编程 PHP编程 Maya动画 Matlab应用 Android
Photoshop Word Excel flash VB编程 VC编程 Coreldraw SolidWorks A Designer Unity3D
 首页 > JSP

在JSP页面中轻松实现数据饼图

51自学网 http://www.51zixue.net
  JSP提供了很多简单实用的工具,其中包括从数据库中读出数据,发送数据,并能够把结果显示在一个饼状图形。现在让我们看看这一简单而实用的方法。

  你所需要的东西

  为了能正确运行这一文章相关的范例,你必须需要JDK 1.2或更高的版本、一个关系数据库管理系统、一个JSP网络服务器。我都是在Tomcat调试这些例子,同时我也使用了Sun Java 2 SDK发布的com.sun.image.codec.jpegclasses。

  数据库设计

  假设你在一家从事销售新鲜水果的公司上班,公司出售的水果包括:苹果、桔子、葡萄。现在你的老板想用一个饼状图形显示每一种水果的总出售量,饼状图形能使每一种产品的销售情况一目了然,老板可以迅速掌握公司的产品成交情况。

  表A使用了本文中的两种数据库列表。第一种列表(Products)包含所有销售产品的名称;第二种列表(Sales)包含每一种产品对应的销售量。

Listing A

Database Design
---------------
p_products table
----------------
productID   int (number)    not null
productname  String (varchar)  not null

p_sales table
-------------
saleID     int (number)   not null
productID   int (number)   not null
amount     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;
}

  我设置以下的数据库规则:

   1、ProductID在产品列表中最独特,也是最关键;

   2、ProductID对于第一个记录的值为0;

   3、所有之后的连续的记录都是累加的,所以第二个记录的productID为1,第三个记录的productID为2,以此类推。

  这些数据库规则允许在product数组中存储数据,如下所示:

arr[rs.getInt("productID")] = rs.getString("productname");


  一些数据库管理系统在缺省情况下就允许数据的自动累加或者自动排序。当你在设计数据库时,一定先查明你的数据库管理系统遵循哪些规则,比如自动累加,自动排序等。

<

 

 

 
上一篇:JSP实现论坛树型结构的具体算法  下一篇:Jsp结合XML+XSLT将输出转换为Html格式