JSP學習——全面解析JDBC(6)
最後更新:2017-02-28
來源:互聯網
上載者:User
js 基於JDBC有哪些資料庫通用存取方法?
1. 通用資料庫Bean設計
本執行個體中對資料庫連接和執行SQL語句等通用資料庫操作進行了封裝,通過實現DBConnBean和DBQueryBean兩個JavaBean來完成上述功能。其中DBConnBean負責Java應用程式和資料庫的串連;DBQueryBean提供了一組執行標準SQL的功能,可以實現標準SQL完成的所有功能。其功能代碼分別如下所示:
① DBConnBean.Java的原始碼如下所示:
package dbaccess;
import Java.sql.*;
import Java.util.*;
import Java.io.*;
public class DBConnBean
implements Serializable{
private String DBDriver = "sun.jdbc.odbc.JdbcOdbcDriver";
private String DBHost = "127.0.0.1";
private String DBName = "demo";
private String conp = "jdbc:odbc:db_demo";
private String username = "";
private String password = "";
private boolean xdebug = true;
public Connection con = null;
public String sql = null;
Statement stmt = null;
public ResultSet result = null;
private int affectedRows = 0;
public DBConnBean()
{
xdebug = true;
con = null;
sql = null;
}
public Connection Connect()
throws Exception
{
String msg = null;
try
{
Class.forName(DBDriver).newInstance();
}
catch(Exception e)
{
msg = "載入資料庫驅動失敗";
if (xdebug) msg += "(驅動'"+DBDriver+"')";
throw new Exception(msg);
}
try
{
String conStr = conp;
con = DriverManager.getConnection(conStr,username,password);
}
catch(SQLException e)
{
msg = "!!資料庫連接失敗";
if (xdebug)
{
msg += "(錯誤資訊='" + e.getMessage()+"' SQL狀態值='" + e.getSQLState()+"' 錯誤碼='" + e.getErrorCode()+"')";
}
throw new Exception(msg);
}
return con;
}
protected void finalize()
throws Throwable
{
super.finalize();
if (stmt != null) stmt.close();
if (result != null) result.close();
}
//最近一次對資料庫查詢受影響的行數
public int getAffectedRows()
{
return affectedRows;
}
public Connection getCon()
{
return con;
}
public String getConp()
{
return conp;
}
public String getDBDriver()
{
return DBDriver;
}
public String getDBName()
{
return DBName;
}
public boolean getDebug()
{
return xdebug;
}
public String getPassword()
{
return password;
}
public ResultSet getResult()
{
return result;
}
public String getSql()
{
return sql;
}
public String getUsername()
{
return username;
}
public void over()
throws Throwable
{
finalize();
}
public ResultSet query()
throws Exception
{
result = null;
affectedRows = 0;
if (con == null)
Connect();
if (stmt == null)
stmt = con.createStatement();
if (sql.substring(0,6).equalsIgnoreCase("select"))
{
result = stmt.executeQuery(sql);
}
else
{
affectedRows = stmt.executeUpdate(sql);
}
return result;
}
public ResultSet query(String s)
throws Exception
{
sql = s;
return query();
}
public void setDBDriver(String s)
{
DBDriver = s;
}
public void setDebug(boolean b)
{
xdebug = b;
}
public void setgetConp(String s)
{
conp = s;
}
public void setgetDBName(String s)
{
DBName = s;
}
public void setgetUsername(String s)
{
username = s;
}
public void setPassword(String s)
{
password = s;
}
public void setSql(String s)
{
sql = s;
}
}
② DBQueryBean.Java的原始碼如下所示:
package dbaccess;
import Java.sql.*;
import Java.util.*;
import Java.io.*;
import Java.lang.reflect.*;
public class DBQueryBean
implements Serializable
{
DBConnBean dbc;
String sql = null;
int rowcount = 0;
int colcount = 0;
// int limitcount = 0;
Vector result = null;
public String _WATCH = "";
public DBQueryBean()
{
dbc = new DBConnBean();
try {
dbc.Connect();
} catch(Exception e) {
handleException(e);
}
}
protected void finalize()
throws Throwable
{
super.finalize();
if (dbc != null) dbc.over();
if (result != null) result.removeAllElements();
}
public String get(int row, int col)
{
if (result==null || row >= result.size()) return null;
String r[] = (String[])result.elementAt(row);
if (col >= Java.lang.reflect.Array.getLength(r)) return null;
return r[col];
}
public int getAffRows() { return dbc.getAffectedRows(); }
public int getColumncount() {
return colcount;
}
public String[] getRow(int row)
{
if (result==null || row >= result.size()) return null;
return (String [])result.elementAt(row);
/*String ret[] = new String[colcount];
Vector r = (Vector)result.elementAt(row);
for (int i=0; i<colcount; i++)
ret[i] = (String)r.elementAt(i);
return ret;*/
}
public int getRowcount() {
return rowcount;
}
public void handleException(Exception e)
{
_WATCH = e.getMessage();
}
public void init()
{
rowcount = 0;
colcount = 0;
// limitcount = 0;
result = null;
}
public void over()
throws Throwable
{
finalize();
}
public int query(String sql)
{
result = new Vector();
int ret = 0;
try {
ResultSet rs = dbc.query(sql);
if (rs == null)
{
ret = dbc.getAffectedRows();
}
else
{
ResultSetMetaData rm = rs.getMetaData();
colcount = rm.getColumnCount();
while (rs.next())
{
String row[] = new String[colcount];
for (int i=0; i<colcount; i++)
row[i] = rs.getString(i+1);
result.addElement(row);
rowcount++;
}
rs.close(); // to release the resource.
ret = result.size();
}
}
catch(Exception e)
{
handleException(e);
return -1;
}
return ret;
}
}
2. 資料庫表結構
本執行個體中主要出現了三個資料庫表,表名和欄位分別如下所示:
計劃採購表:jhcg_table
欄位名稱 中文名稱 類型 長度
Goods_no 物品編號 vchar 10
Goods_name 物品名稱 Vchar 50
Amount 採購數量 Int
Price 採購單價 float
Gold 幣種 Vchar 15
Units 單位 Vchar 10
Date 時間 Date
Remark 備忘 vchar 100
庫存統計表:kctj_table
欄位名稱 中文名稱 類型 長度
Goods_no 物品編號 Vchar 10
Goods_name 物品名稱 Vchar 50
amount 庫存數量 Int
Date 時間 Date
remark 備忘 Vchar 100
實際採購表:sjcg_table
欄位名稱 中文名稱 類型 長度
Goods_no 物品編號 Vchar 10
Goods_name 物品名稱 Vchar 50
Amount 採購數量 Int
Price Price 採購單價 Float
Gold 幣種 Vchar 15
Units 採購單位 Vchar 10
Date 時間 Date
Remark 備忘 vchar 100
其中商務邏輯非常簡單,即根據計劃採購表和庫存統計表產生實際採購表。同時,對各表完成資料庫的增、刪、改、查等通用操作。
3. JSP設計
① 插入操作
完成對資料庫表的記錄插入功能,其中計劃採購表的插入首頁面(insert_jhcg.htm)為:
insert_jhcg.htm將使用者輸入傳送給demo_insert_jhcg.jsp,完成插入操作。改jsp檔案的功能代碼為:
<html>
<body>
<jsp:useBean id="DBConn" class="dbaccess.DBConnBean" scope="page"/>
<jsp:useBean id="DBBean" class="dbaccess.DBQueryBean" scope="page"/>
<hr>
<!--test JavaBean-->
<%
if (DBConn == null||DBBean == null){
out.println("JavaBean not found!");
return;
}
%>
<!--try db_demo connection-->
<%
try{
DBConn.Connect();
}catch(Exception e){
out.println(e.getMessage());
}
%>
<!--execute sql statement-->
<%
String insGoodno = request.getParameter("ed_jhcg_no");
String insGoodname = request.getParameter("ed_jhcg_name");
int insAmount = (Integer.valueOf(request.getParameter("ed_jhcg_amount"))).intValue();
float insPrice = (Float.valueOf(request.getParameter("ed_jhcg_price"))).floatValue();
String insGold = request.getParameter("ed_jhcg_gold");
String insUnit = request.getParameter("ed_jhcg_unit");
String insRemark = request.getParameter("ed_jhcg_remark");
String sqlStatement = "insert into jhcg_table(good_no,good_name,amount,
price,gold,unit,remark) values("+"'"+insGoodno+"'"+","+"'"+insGoodname+"'"+",
"+insAmount+","+insPrice+","+"'"+insGold+"'"+","+"'"+insUnit+"'"+","+"'"+
insRemark+"'"+")";
try{
DBBean.query(sqlStatement);
}catch(Exception e){
out.println(e.getMessage());
}
%>
<a href="demo_main.htm">Records inserted...Click here to return</a></p>
</body>
</html>
② 查詢操作
該查詢首頁面主要提供對三個資料庫表的條件查詢功能,
query.htm將使用者選取查詢的資料庫表和查詢條件發送給demo_query.jsp,由jsp檔案完成資料庫查詢操作和查詢結果集的返回及顯示,其功能代碼如下:
<html>
<body>
<%
String sqlStatement;
String sqlField = "";
String whichTable = "";
String whereClause = "";
String queryNo = "";
String queryName = "";
%>
<jsp:useBean id="DBConn" class="dbaccess.DBConnBean" scope="page"/>
<jsp:useBean id="DBBean" class="dbaccess.DBQueryBean" scope="page"/>
<hr>
<!--test JavaBean-->
<%
if (DBConn == null||DBBean == null){
out.println("JavaBean not found!");
return;
}
%>
<!--try db_demo connection-->
<%
try{
DBConn.Connect();
}catch(Exception e){
out.println(e.getMessage());
}
%>
<!--prepare sql statement-->
<%
String queryRequest = request.getParameter("rb_request");
//out.println("queryRequest:"+queryRequest);
String whichCB = "";
if (queryRequest.equals("1")){
whichCB = "ck_jhcg";
whichTable = "jhcg_table";
queryNo = request.getParameter("ed_jhcg_no");
queryName = request.getParameter("ed_jhcg_name");
if (!queryNo.equals(""))
whereClause = " where good_no="+"'"+queryNo+"'";
if (!queryName.equals("")){
if (!queryNo.equals(""))
whereClause += " and good_name="+"'"+queryName+"'";
else whereClause = " where good_name="+"'"+queryName+"'";
}
}
if (queryRequest.equals("2")){
whichCB = "ck_kctj";
whichTable = "kctj_table";
queryNo = request.getParameter("ed_kctj_no");
queryName = request.getParameter("ed_kctj_name");
if (!queryNo.equals(""))
whereClause = " where good_no="+"'"+queryNo+"'";
if (!queryName.equals("")){
if (!queryNo.equals(""))
whereClause += " and good_name="+"'"+queryName+"'";
else whereClause = " where good_name="+"'"+queryName+"'";
}
}
if (queryRequest.equals("3")){
whichCB = "ck_sjcg";
whichTable = "sjcg_table";
queryNo = request.getParameter("ed_sjcg_no");
queryName = request.getParameter("ed_sjcg_name");
if (!queryNo.equals(""))
whereClause = " where good_no="+"'"+queryNo+"'";
if (!queryName.equals("")){
if (!queryNo.equals(""))
whereClause += " and good_name="+"'"+queryName+"'";
else whereClause = " where good_name="+"'"+queryName+"'";
}
}
String[] printTitle = request.getParameterValues(whichCB);
%>
<!--create query sql statement-->
<%
sqlStatement = "select ";
for(int i = 0;i<printTitle.length;i++){
sqlField += printTitle[i]+",";
}
sqlStatement += sqlField.substring(0,sqlField.length()-1)+" from "+whichTable;
if (!whereClause.equals(""))
sqlStatement += whereClause;
%>
<!--show query response-->
<%
try{
DBBean.query(sqlStatement);
}catch(Exception e){
out.println("Database Error!");
}
int rows = DBBean.getRowcount();
int cols = DBBean.getColumncount();
%>
<Table align="center" width="80%" border=1>
<tr align=center>
<%
for(int i = 0;i < printTitle.length;i++){
out.println("<td><b>");
out.println(printTitle[i]);
out.println("</b></td>");
}
%>
</tr>
<%
for (int i = 0;i < rows;i++){
out.println("<tr>");
for (int j = 0;j < cols;j++)
out.println("<td>"+DBBean.get(i,j)+"</td>");
out.println("</tr>");
}
%>
</Table>
<br>
<hr>
<a href="demo_main.htm">Click here to return</a></p>
</body>
</html>
③ 產生實際採購表
產生資料庫表是一個隱式操作,程式根據計劃採購表和庫存統計表的相應欄位產生實際採購表,不需要使用者的任何輸入,其功能代碼如下(demo_create.jsp):
<%@page import="Java.util.*"%>
<html>
<body>
<jsp:useBean id="DBConn" class="dbaccess.DBConnBean" scope="page"/>
<jsp:useBean id="DBBean" class="dbaccess.DBQueryBean" scope="page"/>
<hr>
<!--test JavaBean-->
<%
if (DBConn == null||DBBean == null){
out.println("JavaBean not found!");
return;
}
%>
<!--try db_demo connection-->
<%
try{
DBConn.Connect();
}catch(Exception e){
out.println(e.getMessage());
}
%>
<!--prepare sql statement-->
<%
int amount_jhcg,amount_kctj;
Vector updateRs = new Vector();
DBBean.query("delete * from sjcg_table"); //delete all old records in sjcg_table
DBBean.query("select jhcg_table.good_no,jhcg_table.good_name,jhcg_table.amount,kctj_table.amount,jhcg_table.unit from jhcg_table left join kctj_table on kctj_table.good_no=jhcg_table.good_no");
int rows = DBBean.getRowcount();
int cols = DBBean.getColumncount();
for (int i = 0;i < rows;i++){
String record[] = new String[4];
record[0] = DBBean.get(i,0);
record[1] = DBBean.get(i,1);
amount_jhcg = (Integer.valueOf(DBBean.get(i,2))).intValue();
if (DBBean.get(i,3) == null) amount_kctj = 0;
else amount_kctj = (Integer.valueOf(DBBean.get(i,3))).intValue();
record[2] = Integer.toString(amount_jhcg - amount_kctj);
record[3] = DBBean.get(i,4);
updateRs.addElement(record);
}
for (int i = 0;i < rows;i++){
String insRecord[] = (String [])updateRs.elementAt(i);
String insGoodno,insGoodname,insUnit,insAmount;
insGoodno = insRecord[0];
insGoodname = insRecord[1];
insAmount = insRecord[2];
insUnit = insRecord[3];
String sqlStatement = "insert into sjcg_table(good_no,good_name,amount,unit) values?quot;+"'"+insGoodno+"'"+","+"'"+insGoodname+"'"+","+insAmount+","+"'"+insUnit+"'"+")";
DBBean.query(sqlStatement);
DBBean.query("delete * from sjcg_table where amount<=0");
}
%>
<a href="demo_main.htm">Database created...Click here to return</a></p>
</body>
</html>
上述的開發工具綜合應用介紹了基於Java開發電子商務應用系統的全過程,包括應用開發平台搭建、商務程序分析、JavaBean封裝和JSP開發等內容,其中JSP開發中涉及到了通用SQL(查詢和插入資料庫表)和遊標操作(產生實際採購表),基本可以完成任何網路資料庫應用的需求。本執行個體基本上可以將前面介紹的基於Java的電子商務開發技術串接起來,指導讀者進行電子商務應用開發。