Servlet中jdbc應用進階篇
來源:互聯網
上載者:User
JDBC使用資料庫URL來說明資料庫驅動程式。資料庫URL類似於通用的URL,但SUN 在定義時作了一點簡化,其文法如下:
Jdbc::[node]/[database]
其中子協議(subprotocal)定義驅動程式類型,node提供網路資料庫的位置和連接埠號碼,後面跟可選的參數。例如:
String url=”jdbc:inetdae:myserver:1433?language=us-english&sql7=true”
表示採用inetdae驅動程式串連1433連接埠上的myserver資料庫伺服器,選擇語言為美國英語,資料庫的版本是mssql server 7.0。
java應用通過指定DriverManager裝入一個驅動程式類。文法如下:
Class.forName(“”);
或
Class.forName(“”).newInstance();
然後,DriverManager建立一個特定的串連:
Connection connection=DriverManager.getConnection(url,login,password);
Connection介面通過指定資料庫位置,登入名稱和密碼串連資料庫。Connection介面建立一個Statement實
例執行需要的查詢:
Statement stmt=connection.createStatement();
Statement具有各種方法(API),如executeQuery,execute等可以返回查詢的結果集。結果集是一個ResultSet對象。具體的可以通過jdbc開發文檔查看。可以sun的網站上下載
下面例子來說明:
import java.sql.*; // 輸入 JDBC package
String url = "jdbc:inetdae:myserver:1433";// 主機名稱和連接埠
String login = "user";// 登入名稱
String password = "";// 密碼
try {
DriverManager.setLogStream(System.out); file://為顯示一些的資訊開啟一個流
file://調用驅動程式,其名字為com.inet.tds.TdsDriver
file://Class.forName("com.inet.tds.TdsDriver");
file://設定逾時
DriverManager.setLoginTimeout(10);
file://開啟一個串連
Connection connection = DriverManager.getConnection(url,login,password);
file://得到資料庫驅動程式版本
DatabaseMetaData conMD = connection.getMetaData();
System.out.println("Driver Name:/t" + conMD.getDriverName());
System.out.println("Driver Version:/t" + conMD.getDriverVersion());
file://選擇資料庫
connection.setCatalog( "MyDatabase");
file://建立Statement
Statement st = connection.createStatement();
file://執行查詢
ResultSet rs = st.executeQuery("SELECT * FROM mytable");
file://取得結果,輸出到螢幕
while (rs.next()){
for(int j=1; j<=rs.getMetaData().getColumnCount(); j++){
System.out.print( rs.getObject(j)+"/t");
}
System.out.println();
}
file://關閉對象
st.close();
connection.close();
} catch(Exception e) {
e.printStackTrace();
}
一個動態網站頻繁地從資料庫中取得資料來構成html頁面。每一次請求一個頁面都會發生資料庫操作。但串連資料庫卻是一個需要消耗大量時間的工作,因為請求串連需要建立通訊,分配資源,進行許可權認證。這些工作很少能在一兩秒內完成。所以,建立一個串連,然後再後續的查詢中都使用此串連會大大地提高效能。因為servlet可以在不同的請求間保持狀態,因此採用資料庫連接池是一個直接的解決方案。
Servlet在伺服器的進程空間中駐留,可以方便而持久地維護資料庫連接。接下來,我們介紹一個完整的串連池的實現。在實現中,有一個串連池管理器管理串連池對象,其中每一個串連池保持一組資料庫連接對象,這些對象可為任何servlet所使用。
一、資料庫連接池類 DBConnectionPool,提供如下的方法:
1、從池中取得一個開啟的串連;
2、將一個串連返回池中;
3、在關閉時釋放所有的資源,並關閉所有的串連。
另外,DBConnectionPool還處理串連失敗,比如逾時,通訊失敗等錯誤,並且根據預定義的參數限制池中的串連數。
二、管理者類,DBConnetionManager,是一個容器將串連池封裝在內,並管理所有的串連池。它的方法有:
1、 調用和註冊所有的jdbc驅動程式;
2、 根據參數表建立DBConnectionPool對象;
3、 映射串連池的名字和DBConnectionPool執行個體;
4、 當所有的串連客戶退出後,關閉全部串連池。
這些類的實現,以及如何在servlet中使用串連池的應用在隨後的文章中講解
DBConnectionPool類代表一個由url標識的資料庫連接池。前面,我們已經提到,jdbc的url由三個部分組成:協議標識(總是jdbc),子協議標識(例如,odbc.oracle),和資料庫標識(跟特定的資料庫有關)。串連池也具有一個名字,供客戶程式引用。另外,串連池還有一個使用者名稱,一個密碼和一個最大允許串連數。如果web應用允許所有的使用者使用某些資料庫操作,而另一些操作是有限制的,則可以建立兩個串連池,具有同樣的url,不同的user name和password,分別處理兩類不同的操作許可權。現把DBConnectionPool詳細介紹如下:
一、DBConnectionPool的構造
建構函式取得上述的所有參數:
public DBConnectionPool(String name, String URL, String user,
String password, int maxConn) {
this.name = name;
this.URL = URL;
this.user = user;
this.password = password;
this.maxConn = maxConn;
}
將所有的參數儲存在執行個體變數中。
二、從池中開啟一個串連
DBConnectionPool提供兩種方法來檢查串連。兩種方法都返回一個可用的串連,如果沒有多餘的串連,則建立一個新的串連。如果最大串連數已經達到,第一個方法返回null,第二個方法則等待一個串連被其他進程釋放。
public synchronized Connection getConnection() {
Connection con = null;
if (freeConnections.size() > 0) {
// Pick the first Connection in the Vector
// to get round-robin usage
con = (Connection) freeConnections.firstElement();
freeConnections.removeElementAt(0);
try {
if (con.isClosed()) {
log("Removed bad connection from " + name);
// Try again recursively
con = getConnection();
}
}
catch (SQLException e) {
log("Removed bad connection from " + name);
// Try again recursively
con = getConnection();
}
}
else if (maxConn == 0 || checkedOut < maxConn) {
con = newConnection();
}
if (con != null) {
checkedOut++;
}
return con;
}
所有閒置連線物件儲存在一個叫freeConnections 的Vector中。如果存在至少一個閒置串連,getConnection()返回其中第一個串連。下面,將會看到,進程釋放的串連返回到freeConnections的末尾。這樣,最大限度地避免了資料庫因一個串連不活動而意外將其關閉的風險。
再返回客戶之前,isClosed()檢查串連是否有效。如果串連被關閉了,或者一個錯誤發生,該方法遞迴調用取得另一個串連。
如果沒有可用的串連,該方法檢查是否最大串連數被設定為0表示無限串連數,或者達到了最大串連數。如果可以建立新的串連,則建立一個新的串連。否則,返回null。
方法newConnection()用來建立一個新的串連。這是一個私人方法,基於使用者名稱和密碼來確定是否可以建立新的串連。
private Connection newConnection() {
Connection con = null;
try {
if (user == null) {
con = DriverManager.getConnection(URL);
}
else {
con = DriverManager.getConnection(URL, user, password);
}
log("Created a new connection in pool " + name);
}
catch (SQLException e) {
log(e, "Can not create a new connection for " + URL);
return null;
}
return con;
}
jdbc的DriverManager提供一系列的getConnection()方法,可以使用url和使用者名稱,密碼等參數建立一個串連。
第二個getConnection()方法帶有一個逾時參數 timeout,當該參數指定的毫秒數表示客戶願意為一個串連等待的時間。這個方法調用前一個方法。
public synchronized Connection getConnection(long timeout) {
long startTime = new Date().getTime();
Connection con;
while ((con = getConnection()) == null) {
try {
wait(timeout);
}
catch (InterruptedException e) {}
if ((new Date().getTime() - startTime) >= timeout) {
// Timeout has expired
return null;
}
}
return con;
}
局部變數startTime初始化當前的時間。一個while迴圈首先嘗試獲得一個串連,如果失敗,wait()函數被調用來等待需要的時間。後面會看到,Wait()函數會在另一個進程調用notify()或者notifyAll()時返回,或者等到時間流逝完畢。為了確定wait()是因為何種原因返回,我們用開始時間減去目前時間,檢查是否大於timeout。如果結果大於timeout,返回null,否則,在此調用getConnection()函數。
四、將一個串連返回池中
DBConnectionPool類中有一個freeConnection方法以返回的串連作為參數,將串連返回串連池。
public synchronized void freeConnection(Connection con) {
// Put the connection at the end of the Vector
freeConnections.addElement(con);
checkedOut--;
notifyAll();
}
串連被加在freeConnections向量的最後,佔用的串連數減1,調用notifyAll()函數通知其他等待的客戶現在有了一個串連。
五、關閉
大多數servlet引擎提供完整的關閉方法。資料庫連接池需要得到通知以正確地關閉所有的串連。DBConnectionManager負責協調關閉事件,但串連由各個串連池自己負責關閉。方法relase()由DBConnectionManager調用。
public synchronized void release() {
Enumeration allConnections = freeConnections.elements();
while (allConnections.hasMoreElements()) {
Connection con = (Connection) allConnections.nextElement();
try {
con.close();
log("Closed connection for pool " + name);
}
catch (SQLException e) {
log(e, "Can not close connection for pool " + name);
}
}
freeConnections.removeAllElements();
}
本方法遍曆freeConnections向量以關閉所有的串連。
DBConnetionManager的建構函式是私人函數,以避免其他類建立其執行個體。
private DBConnectionManager() {
init();
}
DBConnetionManager的客戶調用getInstance()方法來得到該類的單一執行個體的引用。
static synchronized public DBConnectionManager getInstance() {
if (instance == null) {
instance = new DBConnectionManager();
}
clients++;
return instance;
}
單一的執行個體在第一次調用時建立,以後的調用返回該執行個體的靜態應用。一個計數器紀錄所有的客戶數,直到客戶釋放引用。這個計數器在以後用來協調關閉串連池。
一、初始化
建構函式調用一個私人的init()函數初始化對象。
private void init() {
InputStream is = getClass().getResourceAsStream("/db.properties");
Properties dbProps = new Properties();
try {
dbProps.load(is);
}
catch (Exception e) {
System.err.println("Can not read the properties file. " +
"Make sure db.properties is in the CLASSPATH");
return;
}
String logFile = dbProps.getProperty("logfile",
"DBConnectionManager.log");
try {
log = new PrintWriter(new FileWriter(logFile, true), true);
}
catch (IOException e) {
System.err.println("Can not open the log file: " + logFile);
log = new PrintWriter(System.err);
}
loadDrivers(dbProps);
createPools(dbProps);
}
方法getResourceAsStream()是一個標準方法,用來開啟一個外部輸入檔案。檔案的位置取決於類載入器,而標準的類載入器從classpath開始搜尋。Db.properties檔案是一個Porperties格式的檔案,儲存在串連池中定義的key-value對。下面一些常用的屬性可以定義:
drivers 以空格分開的jdbc驅動程式的列表
logfile 記錄檔的絕對路徑
每個串連池中還使用另一些屬性。這些屬性以串連池的名字開頭:
.url資料庫的 JDBC URL
.maxconn最大串連數。0表示無限。
.user串連池的使用者名稱
.password相關的密碼
url屬性是必須的,其他屬性可選。使用者名稱和密碼必須和所定義的資料庫匹配。
下面是windows平台下的一個db.properties檔案的例子。有一個InstantDB串連池和一個通過odbc串連的access資料庫的資料來源,名字叫demo。
drivers=sun.jdbc.odbc.JdbcOdbcDriver jdbc.idbDriver
logfile=D://user//src//java//DBConnectionManager//log.txt
idb.url=jdbc:idb:c://local//javawebserver1.1//db//db.prp
idb.maxconn=2
access.url=jdbc:odbc:demo
access.user=demo
access.password=demopw
注意,反斜線在windows平台下必須雙寫。
初始化方法init()建立一個Porperties對象並裝載db.properties檔案,然後讀取記錄檔屬性。如果記錄檔沒有命名,則使用預設的名字DBConnectionManager.log在目前的目錄下建立。在此情況下,一個系統錯誤被紀錄。
方法loadDrivers()將指定的所有jdbc驅動程式註冊,裝載。
private void loadDrivers(Properties props) {
String driverClasses = props.getProperty("drivers");
StringTokenizer st = new StringTokenizer(driverClasses);
while (st.hasMoreElements()) {
String driverClassName = st.nextToken().trim();
try {
Driver driver = (Driver)
Class.forName(driverClassName).newInstance();
DriverManager.registerDriver(driver);
drivers.addElement(driver);
log("Registered JDBC driver " + driverClassName);
}
catch (Exception e) {
log("Can not register JDBC driver: " +
driverClassName + ", Exception: " + e);
}
}
}
loadDrivers()使用StringTokenizer將dirvers屬性分成單獨的driver串,並將每個驅動程式裝入java虛擬機器。驅動程式的執行個體在 JDBC 的DriverManager中註冊,並加入一個私人的向量drivers中。向量drivers用來關閉和登出所有的驅動程式。
然後,DBConnectionPool對象由私人方法createPools()建立。
private void createPools(Properties props) {
Enumeration propNames = props.propertyNames();
while (propNames.hasMoreElements()) {
String name = (String) propNames.nextElement();
if (name.endsWith(".url")) {
String poolName = name.substring(0, name.lastIndexOf("."));
String url = props.getProperty(poolName + ".url");
if (url == null) {
log("No URL specified for " + poolName);
continue;
}
String user = props.getProperty(poolName + ".user");
String password = props.getProperty(poolName + ".password");
String maxconn = props.getProperty(poolName + ".maxconn", "0");
int max;
try {
max = Integer.valueOf(maxconn).intValue();
}
catch (NumberFormatException e) {
log("Invalid maxconn value " + maxconn + " for " +
poolName);
max = 0;
}
DBConnectionPool pool =
new DBConnectionPool(poolName, url, user, password, max);
pools.put(poolName, pool);
log("Initialized pool " + poolName);
}
}
}
一個枚舉對象儲存所有的屬性名稱,如果屬性名稱帶有.url結尾,則表示是一個串連池對象需要被執行個體化。建立的串連池對象儲存在一個Hashtable執行個體變數中。串連池名字作為索引,串連池對象作為值。
二、得到和返回串連
DBConnectionManager提供getConnection()方法和freeConnection方法,這些方法有客戶程式使用。所有的方法以串連池名字所參數,並調用特定的串連池對象。
public Connection getConnection(String name) {
DBConnectionPool pool = (DBConnectionPool) pools.get(name);
if (pool != null) {
return pool.getConnection();
}
return null;
}
public Connection getConnection(String name, long time) {
DBConnectionPool pool = (DBConnectionPool) pools.get(name);
if (pool != null) {
return pool.getConnection(time);
}
return null;
}
public void freeConnection(String name, Connection con) {
DBConnectionPool pool = (DBConnectionPool) pools.get(name);
if (pool != null) {
pool.freeConnection(con);
}
}
三、關閉
最後,由一個release()方法,用來完好地關閉串連池。每個DBConnectionManager客戶必須調用getInstance()方法引用。有一個計數器跟蹤客戶的數量。方法release()在客戶關閉時調用,技術器減1。當最後一個客戶釋放,DBConnectionManager關閉所有的串連池。
List 11-14
public synchronized void release() {
// Wait until called by the last client
if (--clients != 0) {
return;
}
Enumeration allPools = pools.elements();
while (allPools.hasMoreElements()) {
DBConnectionPool pool = (DBConnectionPool) allPools.nextElement();
pool.release();
}
Enumeration allDrivers = drivers.elements();
while (allDrivers.hasMoreElements()) {
Driver driver = (Driver) allDrivers.nextElement();
try {
DriverManager.deregisterDriver(driver);
log("Deregistered JDBC driver " + driver.getClass().getName());
}
catch (SQLException e) {
log(e, "Can not deregister JDBC driver: " +
driver.getClass().getName());
}
}
}
當所有串連池關閉,所有jdbc驅動程式也被登出。
現在我們結合DBConnetionManager和DBConnectionPool類來講解servlet中串連池的使用:
一、首先簡單介紹一下Servlet的生命週期:
Servlet API定義的servlet生命週期如下:
1、 Servlet 被建立然後初始化(init()方法)。
2、 為0個或多個客戶調用提供服務(service()方法)。
3、 Servlet被銷毀,記憶體被回收(destroy()方法)。
二、servlet中使用串連池的執行個體
使用串連池的servlet有三個階段的典型表現是:
1. 在init()中,調用DBConnectionManager.getInstance()然後將返回的引用儲存在執行個體變數中。
2. 在sevice()中,調用getConnection(),執行一系列資料庫操作,然後調用freeConnection()歸還串連。
3. 在destroy()中,調用release()來釋放所有的資源,並關閉所有的串連。
下面的例子示範如何使用串連池。
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class TestServlet extends HttpServlet {
private DBConnectionManager connMgr;
public void init(ServletConfig conf) throws ServletException {
super.init(conf);
connMgr = DBConnectionManager.getInstance();
}
public void service(HttpServletRequest req, HttpServletResponse res)
throws IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
Connection con = connMgr.getConnection("idb");
if (con == null) {
out.println("Cant get connection");
return;
}
ResultSet rs = null;
ResultSetMetaData md = null;
Statement stmt = null;
try {
stmt = con.createStatement();
rs = stmt.executeQuery("SELECT * FROM EMPLOYEE");
md = rs.getMetaData();
out.println("
Employee data
");
while (rs.next()) {
out.println("
");
for (int i = 1; i < md.getColumnCount(); i++) {
out.print(rs.getString(i) + ", ");
}
}
stmt.close();
rs.close();
}
catch (SQLException e) {
e.printStackTrace(out);
}
connMgr.freeConnection("idb", con);
}
public void destroy() {
connMgr.release();
super.destroy();
}
}