top
Loading...
在JSP頁面中輕松實現數據餅圖


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 floatnot 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");

一些數據庫管理系統在缺省情況下就允許數據的自動累加或者自動排序。當你在設計數據庫時,一定先查明你的數據庫管理系統遵循哪些規則,比如自動累加,自動排序等。

作者:http://www.zhujiangroad.com
來源:http://www.zhujiangroad.com
北斗有巢氏 有巢氏北斗