連結(jié)數(shù)據(jù)庫
JDBC使用數(shù)據(jù)庫URL來說明數(shù)據(jù)庫驅(qū)動程序。數(shù)據(jù)庫URL類似于通用的URL,但SUN 在定義時作了一點(diǎn)簡化,其語法如下:
Jdbc::[node]/[database]
其中子協(xié)議(subprotocal)定義驅(qū)動程序類型,node提供網(wǎng)絡(luò)數(shù)據(jù)庫的位置和端口號,后面跟可選的參數(shù)。例如:
String url=”jdbc:inetdae:myserver:1433?language=us-english&sql7=true”
表示采用inetdae驅(qū)動程序連接1433端口上的myserver數(shù)據(jù)庫服務(wù)器,選擇語言為美國英語,數(shù)據(jù)庫的版本是mssql server 7.0。
java應(yīng)用通過指定DriverManager裝入一個驅(qū)動程序類。語法如下:
Class.forName(“”);
或
Class.forName(“”).newInstance();
然后,DriverManager創(chuàng)建一個特定的連接:
Connection connection=DriverManager.getConnection(url,login,password);
Connection接口通過指定數(shù)據(jù)庫位置,登錄名和密碼連接數(shù)據(jù)庫。Connection接口創(chuàng)建一個Statement實(shí)例執(zhí)行需要的查詢:
Statement stmt=connection.createStatement();
Statement具有各種方法(API),如executeQuery,execute等可以返回查詢的結(jié)果集。結(jié)果集是一個ResultSet對象。具體的可以通過jdbc開發(fā)文檔查看。可以sun的站點(diǎn)上下載
下面例子來說明:
import java.sql.*; // 輸入JDBC package
String url = "jdbc:inetdae:myserver:1433";// 主機(jī)名和端口
String login = "user";// 登錄名
String password = "";// 密碼
try {
DriverManager.setLogStream(System.out); file://為顯示一些的信息打開一個流
file://調(diào)用驅(qū)動程序,其名字為com.inet.tds.TdsDriver
file://Class.forName("com.inet.tds.TdsDriver");
file://設(shè)置超時
DriverManager.setLoginTimeout(10);
file://打開一個連接
Connection connection = DriverManager.getConnection(url,login,password);
file://得到數(shù)據(jù)庫驅(qū)動程序版本
DatabaseMetaData conMD = connection.getMetaData();
System.out.println("Driver Name:\t" + conMD.getDriverName());
System.out.println("Driver Version:\t" + conMD.getDriverVersion());
file://選擇數(shù)據(jù)庫
connection.setCatalog( "MyDatabase");
file://創(chuàng)建Statement
Statement st = connection.createStatement();
file://執(zhí)行查詢
ResultSet rs = st.executeQuery("SELECT * FROM mytable");
file://取得結(jié)果,輸出到屏幕
while (rs.next()){
for(int j=1; j<=rs.getMetaData().getColumnCount(); j++){
System.out.print( rs.getObject(j)+"\t");
}
System.out.println();
}
file://關(guān)閉對象
st.close();
connection.close();
} catch(Exception e) {
e.printStackTrace();
}
建立連結(jié)池
一個動態(tài)的網(wǎng)站頻繁地從數(shù)據(jù)庫中取得數(shù)據(jù)來構(gòu)成html頁面。每一次請求一個頁面都會發(fā)生數(shù)據(jù)庫操作。但連接數(shù)據(jù)庫卻是一個需要消耗大量時間的工作,因?yàn)檎埱筮B接需要建立通訊,分配資源,進(jìn)行權(quán)限認(rèn)證。這些工作很少能在一兩秒內(nèi)完成。所以,建立一個連接,然后再后續(xù)的查詢中都使用此連接會大大地提高性能。因?yàn)閟ervlet可以在不同的請求間保持狀態(tài),因此采用數(shù)據(jù)庫連接池是一個直接的解決方案。
Servlet在服務(wù)器的進(jìn)程空間中駐留,可以方便而持久地維護(hù)數(shù)據(jù)庫連接。接下來,我們介紹一個完整的連接池的實(shí)現(xiàn)。在實(shí)現(xiàn)中,有一個連接池管理器管理連接池對象,其中每一個連接池保持一組數(shù)據(jù)庫連接對象,這些對象可為任何servlet所使用。
一、數(shù)據(jù)庫連接池類 DBConnectionPool,提供如下的方法:
1、從池中取得一個打開的連接;
2、將一個連接返回池中;
3、在關(guān)閉時釋放所有的資源,并關(guān)閉所有的連接。
另外,DBConnectionPool還處理連接失敗,比如超時,通訊失敗等錯誤,并且根據(jù)預(yù)定義的參數(shù)限制池中的連接數(shù)。
二、管理者類,DBConnetionManager,是一個容器將連接池封裝在內(nèi),并管理所有的連接池。它的方法有:
1、 調(diào)用和注冊所有的jdbc驅(qū)動程序;
2、 根據(jù)參數(shù)表創(chuàng)建DBConnectionPool對象;
3、 映射連接池的名字和DBConnectionPool實(shí)例;
4、 當(dāng)所有的連接客戶退出后,關(guān)閉全部連接池。
這些類的實(shí)現(xiàn),以及如何在servlet中使用連接池的應(yīng)用在隨后的文章中講解
DBConnectionPool類代表一個由url標(biāo)識的數(shù)據(jù)庫連接池。前面,我們已經(jīng)提到,jdbc的url由三個部分組成:協(xié)議標(biāo)識(總是jdbc),子協(xié)議標(biāo)識(例如,odbc.oracle),和數(shù)據(jù)庫標(biāo)識(跟特定的數(shù)據(jù)庫有關(guān))。連接池也具有一個名字,供客戶程序引用。另外,連接池還有一個用戶名,一個密碼和一個最大允許連接數(shù)。如果web應(yīng)用允許所有的用戶使用某些數(shù)據(jù)庫操作,而另一些操作是有限制的,則可以創(chuàng)建兩個連接池,具有同樣的url,不同的user name和password,分別處理兩類不同的操作權(quán)限?,F(xiàn)把DBConnectionPool詳細(xì)介紹如下:
三、DBConnectionPool的構(gòu)造
構(gòu)造函數(shù)取得上述的所有參數(shù):
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;
}
將所有的參數(shù)保存在實(shí)例變量中。
四、從池中打開一個連接
DBConnectionPool提供兩種方法來檢查連接。兩種方法都返回一個可用的連接,如果沒有多余的連接,則創(chuàng)建一個新的連接。如果最大連接數(shù)已經(jīng)達(dá)到,第一個方法返回null,第二個方法則等待一個連接被其他進(jìn)程釋放。
public synchronized Connection getConnection() {
Connection con = null;
if (freeConnections.size() > 0) {
// Pick the first Connection in the Vector
// to get round-robin usage
// to http://www.knowsky.com
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()返回其中第一個連接。下面,將會看到,進(jìn)程釋放的連接返回到freeConnections的末尾。這樣,最大限度地避免了數(shù)據(jù)庫因一個連接不活動而意外將其關(guān)閉的風(fēng)險。
再返回客戶之前,isClosed()檢查連接是否有效。如果連接被關(guān)閉了,或者一個錯誤發(fā)生,該方法遞歸調(diào)用取得另一個連接。
如果沒有可用的連接,該方法檢查是否最大連接數(shù)被設(shè)置為0表示無限連接數(shù),或者達(dá)到了最大連接數(shù)。如果可以創(chuàng)建新的連接,則創(chuàng)建一個新的連接。否則,返回null。
方法newConnection()用來創(chuàng)建一個新的連接。這是一個私有方法,基于用戶名和密碼來確定是否可以創(chuàng)建新的連接。
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和用戶名,密碼等參數(shù)創(chuàng)建一個連接。
第二個getConnection()方法帶有一個超時參數(shù) timeout,當(dāng)該參數(shù)指定的毫秒數(shù)表示客戶愿意為一個連接等待的時間。這個方法調(diào)用前一個方法。
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初始化當(dāng)前的時間。一個while循環(huán)首先嘗試獲得一個連接,如果失敗,wait()函數(shù)被調(diào)用來等待需要的時間。后面會看到,Wait()函數(shù)會在另一個進(jìn)程調(diào)用notify()或者notifyAll()時返回,或者等到時間流逝完畢。為了確定wait()是因?yàn)楹畏N原因返回,我們用開始時間減去當(dāng)前時間,檢查是否大于timeout。如果結(jié)果大于timeout,返回null,否則,在此調(diào)用getConnection()函數(shù)。
五、將一個連接返回池中
DBConnectionPool類中有一個freeConnection方法以返回的連接作為參數(shù),將連接返回連接池。
public synchronized void freeConnection(Connection con) {
// Put the connection at the end of the Vector
freeConnections.addElement(con);
checkedOut--;
notifyAll();
}
連接被加在freeConnections向量的最后,占用的連接數(shù)減1,調(diào)用notifyAll()函數(shù)通知其他等待的客戶現(xiàn)在有了一個連接。
六、關(guān)閉
大多數(shù)servlet引擎提供完整的關(guān)閉方法。數(shù)據(jù)庫連接池需要得到通知以正確地關(guān)閉所有的連接。DBConnectionManager負(fù)責(zé)協(xié)調(diào)關(guān)閉事件,但連接由各個連接池自己負(fù)責(zé)關(guān)閉。方法relase()由DBConnectionManager調(diào)用。
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向量以關(guān)閉所有的連接。
DBConnetionManager的構(gòu)造函數(shù)是私有函數(shù),以避免其他類創(chuàng)建其實(shí)例。
private DBConnectionManager() {
init();
}
DBConnetionManager的客戶調(diào)用getInstance()方法來得到該類的單一實(shí)例的引用。
static synchronized public DBConnectionManager getInstance() {
if (instance == null) {
instance = new DBConnectionManager();
}
clients++;
return instance;
}
連結(jié)池使用實(shí)例
單一的實(shí)例在第一次調(diào)用時創(chuàng)建,以后的調(diào)用返回該實(shí)例的靜態(tài)應(yīng)用。一個計(jì)數(shù)器紀(jì)錄所有的客戶數(shù),直到客戶釋放引用。這個計(jì)數(shù)器在以后用來協(xié)調(diào)關(guān)閉連接池。
一、初始化
構(gòu)造函數(shù)調(diào)用一個私有的init()函數(shù)初始化對象。
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()是一個標(biāo)準(zhǔn)方法,用來打開一個外部輸入文件。文件的位置取決于類加載器,而標(biāo)準(zhǔn)的類加載器從classpath開始搜索。Db.properties文件是一個Porperties格式的文件,保存在連接池中定義的key-value對。下面一些常用的屬性可以定義:
drivers 以空格分開的jdbc驅(qū)動程序的列表
logfile 日志文件的絕對路徑
每個連接池中還使用另一些屬性。這些屬性以連接池的名字開頭:
.url數(shù)據(jù)庫的JDBC URL
.maxconn最大連接數(shù)。0表示無限。
.user連接池的用戶名
.password相關(guān)的密碼
url屬性是必須的,其他屬性可選。用戶名和密碼必須和所定義的數(shù)據(jù)庫匹配。
下面是windows平臺下的一個db.properties文件的例子。有一個InstantDB連接池和一個通過odbc連接的access數(shù)據(jù)庫的數(shù)據(jù)源,名字叫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()創(chuàng)建一個Porperties對象并裝載db.properties文件,然后讀取日志文件屬性。如果日志文件沒有命名,則使用缺省的名字DBConnectionManager.log在當(dāng)前目錄下創(chuàng)建。在此情況下,一個系統(tǒng)錯誤被紀(jì)錄。
方法loadDrivers()將指定的所有jdbc驅(qū)動程序注冊,裝載。
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屬性分成單獨(dú)的driver串,并將每個驅(qū)動程序裝入java虛擬機(jī)。驅(qū)動程序的實(shí)例在JDBC 的DriverManager中注冊,并加入一個私有的向量drivers中。向量drivers用來關(guān)閉和注銷所有的驅(qū)動程序。
然后,DBConnectionPool對象由私有方法createPools()創(chuàng)建。
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結(jié)尾,則表示是一個連接池對象需要被實(shí)例化。創(chuàng)建的連接池對象保存在一個Hashtable實(shí)例變量中。連接池名字作為索引,連接池對象作為值。
二、得到和返回連接
DBConnectionManager提供getConnection()方法和freeConnection方法,這些方法有客戶程序使用。所有的方法以連接池名字所參數(shù),并調(diào)用特定的連接池對象。
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);
}
}
三、關(guān)閉
最后,由一個release()方法,用來完好地關(guān)閉連接池。每個DBConnectionManager客戶必須調(diào)用getInstance()方法引用。有一個計(jì)數(shù)器跟蹤客戶的數(shù)量。方法release()在客戶關(guān)閉時調(diào)用,技術(shù)器減1。當(dāng)最后一個客戶釋放,DBConnectionManager關(guān)閉所有的連接池。
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());
}
}
}
當(dāng)所有連接池關(guān)閉,所有jdbc驅(qū)動程序也被注銷。
連結(jié)池的作用
現(xiàn)在我們結(jié)合DBConnetionManager和DBConnectionPool類來講解servlet中連接池的使用:
一、首先簡單介紹一下Servlet的生命周期:
Servlet API定義的servlet生命周期如下:
1、 Servlet 被創(chuàng)建然后初始化(init()方法)。
2、 為0個或多個客戶調(diào)用提供服務(wù)(service()方法)。
3、 Servlet被銷毀,內(nèi)存被回收(destroy()方法)。
二、servlet中使用連接池的實(shí)例
使用連接池的servlet有三個階段的典型表現(xiàn)是:
1. 在init()中,調(diào)用DBConnectionManager.getInstance()然后將返回的引用保存在實(shí)例變量中。
2. 在sevice()中,調(diào)用getConnection(),執(zhí)行一系列數(shù)據(jù)庫操作,然后調(diào)用freeConnection()歸還連接。
3. 在destroy()中,調(diào)用release()來釋放所有的資源,并關(guān)閉所有的連接。
下面的例子演示如何使用連接池。
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();
}
}