連結(jié)數(shù)據(jù)庫(kù)

  JDBC使用數(shù)據(jù)庫(kù)URL來(lái)說(shuō)明數(shù)據(jù)庫(kù)驅(qū)動(dòng)程序。數(shù)據(jù)庫(kù)URL類(lèi)似于通用的URL,但SUN 在定義時(shí)作了一點(diǎn)簡(jiǎn)化,其語(yǔ)法如下:

  Jdbc::[node]/[database]

  其中子協(xié)議(subprotocal)定義驅(qū)動(dòng)程序類(lèi)型,node提供網(wǎng)絡(luò)數(shù)據(jù)庫(kù)的位置和端口號(hào),后面跟可選的參數(shù)。例如:

String url=”jdbc:inetdae:myserver:1433?language=us-english&sql7=true

  表示采用inetdae驅(qū)動(dòng)程序連接1433端口上的myserver數(shù)據(jù)庫(kù)服務(wù)器,選擇語(yǔ)言為美國(guó)英語(yǔ),數(shù)據(jù)庫(kù)的版本是mssql server 7.0。

  java應(yīng)用通過(guò)指定DriverManager裝入一個(gè)驅(qū)動(dòng)程序類(lèi)。語(yǔ)法如下:

Class.forName(“”);

  或  

Class.forName(“”).newInstance();

  然后,DriverManager創(chuàng)建一個(gè)特定的連接:

Connection connection=DriverManager.getConnection(url,login,password);

  Connection接口通過(guò)指定數(shù)據(jù)庫(kù)位置,登錄名和密碼連接數(shù)據(jù)庫(kù)。Connection接口創(chuàng)建一個(gè)Statement實(shí)例執(zhí)行需要的查詢(xún):

Statement stmt=connection.createStatement();

  Statement具有各種方法(API),如executeQuery,execute等可以返回查詢(xún)的結(jié)果集。結(jié)果集是一個(gè)ResultSet對(duì)象。具體的可以通過(guò)jdbc開(kāi)發(fā)文檔查看。可以sun的站點(diǎn)上下載

  下面例子來(lái)說(shuō)明:

importjava.sql.*; // 輸入JDBC package

String url = "jdbc:inetdae:myserver:1433";// 主機(jī)名和端口
String login = "user";// 登錄名
String password = "";// 密碼

try {
  DriverManager.setLogStream(System.out); file://為顯示一些的信息打開(kāi)一個(gè)流
  file://調(diào)用驅(qū)動(dòng)程序,其名字為com.inet.tds.TdsDriver
  file://Class.forName("com.inet.tds.TdsDriver");
  file://設(shè)置超時(shí)
  DriverManager.setLoginTimeout(10);
  file://打開(kāi)一個(gè)連接
  Connection connection = DriverManager.getConnection(url,login,password);
  file://得到數(shù)據(jù)庫(kù)驅(qū)動(dòng)程序版本

   DatabaseMetaData conMD = connection.getMetaData();
   System.out.println("DriverName:\t" + conMD.getDriverName());
   System.out.println("DriverVersion:\t" + conMD.getDriverVersion());

  file://選擇數(shù)據(jù)庫(kù)
  connection.setCatalog( "MyDatabase");

  file://創(chuàng)建Statement

  Statement st = connection.createStatement();

  file://執(zhí)行查詢(xún)

  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)閉對(duì)象
  st.close();
    connection.close();
  } catch(Exception e) {
    e.printStackTrace();
  }



建立連結(jié)池

  一個(gè)動(dòng)態(tài)的網(wǎng)站頻繁地從數(shù)據(jù)庫(kù)中取得數(shù)據(jù)來(lái)構(gòu)成html頁(yè)面。每一次請(qǐng)求一個(gè)頁(yè)面都會(huì)發(fā)生數(shù)據(jù)庫(kù)操作。但連接數(shù)據(jù)庫(kù)卻是一個(gè)需要消耗大量時(shí)間的工作,因?yàn)檎?qǐng)求連接需要建立通訊,分配資源,進(jìn)行權(quán)限認(rèn)證。這些工作很少能在一兩秒內(nèi)完成。所以,建立一個(gè)連接,然后再后續(xù)的查詢(xún)中都使用此連接會(huì)大大地提高性能。因?yàn)閟ervlet可以在不同的請(qǐng)求間保持狀態(tài),因此采用數(shù)據(jù)庫(kù)連接池是一個(gè)直接的解決方案。

  Servlet在服務(wù)器的進(jìn)程空間中駐留,可以方便而持久地維護(hù)數(shù)據(jù)庫(kù)連接。接下來(lái),我們介紹一個(gè)完整的連接池的實(shí)現(xiàn)。在實(shí)現(xiàn)中,有一個(gè)連接池管理器管理連接池對(duì)象,其中每一個(gè)連接池保持一組數(shù)據(jù)庫(kù)連接對(duì)象,這些對(duì)象可為任何servlet所使用。

  一、數(shù)據(jù)庫(kù)連接池類(lèi) DBConnectionPool,提供如下的方法:

  1、從池中取得一個(gè)打開(kāi)的連接;

  2、將一個(gè)連接返回池中;

  3、在關(guān)閉時(shí)釋放所有的資源,并關(guān)閉所有的連接。

  另外,DBConnectionPool還處理連接失敗,比如超時(shí),通訊失敗等錯(cuò)誤,并且根據(jù)預(yù)定義的參數(shù)限制池中的連接數(shù)。

  二、管理者類(lèi),DBConnetionManager,是一個(gè)容器將連接池封裝在內(nèi),并管理所有的連接池。它的方法有:

  1、 調(diào)用和注冊(cè)所有的jdbc驅(qū)動(dòng)程序;

  2、 根據(jù)參數(shù)表創(chuàng)建DBConnectionPool對(duì)象;

  3、 映射連接池的名字和DBConnectionPool實(shí)例;

  4、 當(dāng)所有的連接客戶(hù)退出后,關(guān)閉全部連接池。

  這些類(lèi)的實(shí)現(xiàn),以及如何在servlet中使用連接池的應(yīng)用在隨后的文章中講解

  DBConnectionPool類(lèi)代表一個(gè)由url標(biāo)識(shí)的數(shù)據(jù)庫(kù)連接池。前面,我們已經(jīng)提到,jdbc的url由三個(gè)部分組成:協(xié)議標(biāo)識(shí)(總是jdbc),子協(xié)議標(biāo)識(shí)(例如,odbc.oracle),和數(shù)據(jù)庫(kù)標(biāo)識(shí)(跟特定的數(shù)據(jù)庫(kù)有關(guān))。連接池也具有一個(gè)名字,供客戶(hù)程序引用。另外,連接池還有一個(gè)用戶(hù)名,一個(gè)密碼和一個(gè)最大允許連接數(shù)。如果web應(yīng)用允許所有的用戶(hù)使用某些數(shù)據(jù)庫(kù)操作,而另一些操作是有限制的,則可以創(chuàng)建兩個(gè)連接池,具有同樣的url,不同的user name和password,分別處理兩類(lèi)不同的操作權(quán)限。現(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í)例變量中。

  四、從池中打開(kāi)一個(gè)連接

  DBConnectionPool提供兩種方法來(lái)檢查連接。兩種方法都返回一個(gè)可用的連接,如果沒(méi)有多余的連接,則創(chuàng)建一個(gè)新的連接。如果最大連接數(shù)已經(jīng)達(dá)到,第一個(gè)方法返回null,第二個(gè)方法則等待一個(gè)連接被其他進(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
  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;
}

  所有空閑的連接對(duì)象保存在一個(gè)叫freeConnections 的Vector中。如果存在至少一個(gè)空閑的連接,getConnection()返回其中第一個(gè)連接。下面,將會(huì)看到,進(jìn)程釋放的連接返回到freeConnections的末尾。這樣,最大限度地避免了數(shù)據(jù)庫(kù)因一個(gè)連接不活動(dòng)而意外將其關(guān)閉的風(fēng)險(xiǎn)。

  再返回客戶(hù)之前,isClosed()檢查連接是否有效。如果連接被關(guān)閉了,或者一個(gè)錯(cuò)誤發(fā)生,該方法遞歸調(diào)用取得另一個(gè)連接。

  如果沒(méi)有可用的連接,該方法檢查是否最大連接數(shù)被設(shè)置為0表示無(wú)限連接數(shù),或者達(dá)到了最大連接數(shù)。如果可以創(chuàng)建新的連接,則創(chuàng)建一個(gè)新的連接。否則,返回null。

  方法newConnection()用來(lái)創(chuàng)建一個(gè)新的連接。這是一個(gè)私有方法,基于用戶(hù)名和密碼來(lái)確定是否可以創(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和用戶(hù)名,密碼等參數(shù)創(chuàng)建一個(gè)連接。

  第二個(gè)getConnection()方法帶有一個(gè)超時(shí)參數(shù) timeout,當(dāng)該參數(shù)指定的毫秒數(shù)表示客戶(hù)愿意為一個(gè)連接等待的時(shí)間。這個(gè)方法調(diào)用前一個(gè)方法。

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)前的時(shí)間。一個(gè)while循環(huán)首先嘗試獲得一個(gè)連接,如果失敗,wait()函數(shù)被調(diào)用來(lái)等待需要的時(shí)間。后面會(huì)看到,Wait()函數(shù)會(huì)在另一個(gè)進(jìn)程調(diào)用notify()或者notifyAll()時(shí)返回,或者等到時(shí)間流逝完畢。為了確定wait()是因?yàn)楹畏N原因返回,我們用開(kāi)始時(shí)間減去當(dāng)前時(shí)間,檢查是否大于timeout。如果結(jié)果大于timeout,返回null,否則,在此調(diào)用getConnection()函數(shù)。

  五、將一個(gè)連接返回池中

  DBConnectionPool類(lèi)中有一個(gè)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ù)通知其他等待的客戶(hù)現(xiàn)在有了一個(gè)連接。

  六、關(guān)閉

  大多數(shù)servlet引擎提供完整的關(guān)閉方法。數(shù)據(jù)庫(kù)連接池需要得到通知以正確地關(guān)閉所有的連接。DBConnectionManager負(fù)責(zé)協(xié)調(diào)關(guān)閉事件,但連接由各個(gè)連接池自己負(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ù),以避免其他類(lèi)創(chuàng)建其實(shí)例。

private DBConnectionManager() {

init();

}

  DBConnetionManager的客戶(hù)調(diào)用getInstance()方法來(lái)得到該類(lèi)的單一實(shí)例的引用。

static synchronized public DBConnectionManager getInstance() {
if (instance == null) {
 instance = new DBConnectionManager();
}
clients++;
return instance;
}



連結(jié)池使用實(shí)例

  單一的實(shí)例在第一次調(diào)用時(shí)創(chuàng)建,以后的調(diào)用返回該實(shí)例的靜態(tài)應(yīng)用。一個(gè)計(jì)數(shù)器紀(jì)錄所有的客戶(hù)數(shù),直到客戶(hù)釋放引用。這個(gè)計(jì)數(shù)器在以后用來(lái)協(xié)調(diào)關(guān)閉連接池。

  一、初始化

  構(gòu)造函數(shù)調(diào)用一個(gè)私有的init()函數(shù)初始化對(duì)象。

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()是一個(gè)標(biāo)準(zhǔn)方法,用來(lái)打開(kāi)一個(gè)外部輸入文件。文件的位置取決于類(lèi)加載器,而標(biāo)準(zhǔn)的類(lèi)加載器從classpath開(kāi)始搜索。Db.properties文件是一個(gè)Porperties格式的文件,保存在連接池中定義的key-value對(duì)。下面一些常用的屬性可以定義:

   drivers 以空格分開(kāi)的jdbc驅(qū)動(dòng)程序的列表

   logfile 日志文件的絕對(duì)路徑

  每個(gè)連接池中還使用另一些屬性。這些屬性以連接池的名字開(kāi)頭:

   .url數(shù)據(jù)庫(kù)的JDBC URL

   .maxconn最大連接數(shù)。0表示無(wú)限。

   .user連接池的用戶(hù)名

   .password相關(guān)的密碼

  url屬性是必須的,其他屬性可選。用戶(hù)名和密碼必須和所定義的數(shù)據(jù)庫(kù)匹配。

  下面是windows平臺(tái)下的一個(gè)db.properties文件的例子。有一個(gè)InstantDB連接池和一個(gè)通過(guò)odbc連接的access數(shù)據(jù)庫(kù)的數(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平臺(tái)下必須雙寫(xiě)。

  初始化方法init()創(chuàng)建一個(gè)Porperties對(duì)象并裝載db.properties文件,然后讀取日志文件屬性。如果日志文件沒(méi)有命名,則使用缺省的名字DBConnectionManager.log在當(dāng)前目錄下創(chuàng)建。在此情況下,一個(gè)系統(tǒng)錯(cuò)誤被紀(jì)錄。

  方法loadDrivers()將指定的所有jdbc驅(qū)動(dòng)程序注冊(cè),裝載。

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串,并將每個(gè)驅(qū)動(dòng)程序裝入java虛擬機(jī)。驅(qū)動(dòng)程序的實(shí)例在JDBC 的DriverManager中注冊(cè),并加入一個(gè)私有的向量drivers中。向量drivers用來(lái)關(guān)閉和注銷(xiāo)所有的驅(qū)動(dòng)程序。

  然后,DBConnectionPool對(duì)象由私有方法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);
  }
 }
}

  一個(gè)枚舉對(duì)象保存所有的屬性名,如果屬性名帶有.url結(jié)尾,則表示是一個(gè)連接池對(duì)象需要被實(shí)例化。創(chuàng)建的連接池對(duì)象保存在一個(gè)Hashtable實(shí)例變量中。連接池名字作為索引,連接池對(duì)象作為值。

  二、得到和返回連接

  DBConnectionManager提供getConnection()方法和freeConnection方法,這些方法有客戶(hù)程序使用。所有的方法以連接池名字所參數(shù),并調(diào)用特定的連接池對(duì)象。

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)閉

  最后,由一個(gè)release()方法,用來(lái)完好地關(guān)閉連接池。每個(gè)DBConnectionManager客戶(hù)必須調(diào)用getInstance()方法引用。有一個(gè)計(jì)數(shù)器跟蹤客戶(hù)的數(shù)量。方法release()在客戶(hù)關(guān)閉時(shí)調(diào)用,技術(shù)器減1。當(dāng)最后一個(gè)客戶(hù)釋放,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ū)動(dòng)程序也被注銷(xiāo)。


連結(jié)池的作用

  現(xiàn)在我們結(jié)合DBConnetionManager和DBConnectionPool類(lèi)來(lái)講解servlet中連接池的使用:

  一、首先簡(jiǎn)單介紹一下Servlet的生命周期:

  Servlet API定義的servlet生命周期如下:

  1、 Servlet 被創(chuàng)建然后初始化(init()方法)。

  2、 為0個(gè)或多個(gè)客戶(hù)調(diào)用提供服務(wù)(service()方法)。

  3、 Servlet被銷(xiāo)毀,內(nèi)存被回收(destroy()方法)。

  二、servlet中使用連接池的實(shí)例

  使用連接池的servlet有三個(gè)階段的典型表現(xiàn)是:

  1. 在init()中,調(diào)用DBConnectionManager.getInstance()然后將返回的引用保存在實(shí)例變量中。

  2. 在sevice()中,調(diào)用getConnection(),執(zhí)行一系列數(shù)據(jù)庫(kù)操作,然后調(diào)用freeConnection()歸還連接。

  3. 在destroy()中,調(diào)用release()來(lái)釋放所有的資源,并關(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();
 }
}

??