乡下人产国偷v产偷v自拍,国产午夜片在线观看,婷婷成人亚洲综合国产麻豆,久久综合给合久久狠狠狠9

  • <output id="e9wm2"></output>
    <s id="e9wm2"><nobr id="e9wm2"><ins id="e9wm2"></ins></nobr></s>

    • 分享

      Servlet開發(fā)中JDBC的高級應用

       duduwolf 2005-09-24

        連結數(shù)據(jù)庫

        JDBC使用數(shù)據(jù)庫URL來說明數(shù)據(jù)庫驅(qū)動程序。數(shù)據(jù)庫URL類似于通用的URL,但SUN 在定義時作了一點簡化,其語法如下:

        Jdbc::[node]/[database]

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

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

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

        java應用通過指定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實例執(zhí)行需要的查詢:

      Statement stmt=connection.createStatement(); 

        Statement具有各種方法(API),如executeQuery,execute等可以返回查詢的結果集。結果集是一個ResultSet對象。具體的可以通過jdbc開發(fā)文檔查看??梢詓un的站點上下載

        下面例子來說明:

      import java.sql.*; // 輸入JDBC package

      String url = "jdbc:inetdae:myserver:1433";// 主機名和端口
      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://設置超時
        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://取得結果,輸出到屏幕

        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();
        } 
        建立連結池

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

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

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

        1、從池中取得一個打開的連接;

        2、將一個連接返回池中;

        3、在關閉時釋放所有的資源,并關閉所有的連接。

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

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

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

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

        3、 映射連接池的名字和DBConnectionPool實例;

        4、 當所有的連接客戶退出后,關閉全部連接池。

        這些類的實現(xiàn),以及如何在servlet中使用連接池的應用在隨后的文章中講解

        DBConnectionPool類代表一個由url標識的數(shù)據(jù)庫連接池。前面,我們已經(jīng)提到,jdbc的url由三個部分組成:協(xié)議標識(總是jdbc),子協(xié)議標識(例如,odbc.oracle),和數(shù)據(jù)庫標識(跟特定的數(shù)據(jù)庫有關)。連接池也具有一個名字,供客戶程序引用。另外,連接池還有一個用戶名,一個密碼和一個最大允許連接數(shù)。如果web應用允許所有的用戶使用某些數(shù)據(jù)庫操作,而另一些操作是有限制的,則可以創(chuàng)建兩個連接池,具有同樣的url,不同的user name和password,分別處理兩類不同的操作權限?,F(xiàn)把DBConnectionPool詳細介紹如下:

        三、DBConnectionPool的構造

        構造函數(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ù)保存在實例變量中。

        四、從池中打開一個連接

        DBConnectionPool提供兩種方法來檢查連接。兩種方法都返回一個可用的連接,如果沒有多余的連接,則創(chuàng)建一個新的連接。如果最大連接數(shù)已經(jīng)達到,第一個方法返回null,第二個方法則等待一個連接被其他進程釋放。

      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.
        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的末尾。這樣,最大限度地避免了數(shù)據(jù)庫因一個連接不活動而意外將其關閉的風險。

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

        如果沒有可用的連接,該方法檢查是否最大連接數(shù)被設置為0表示無限連接數(shù),或者達到了最大連接數(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,當該參數(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初始化當前的時間。一個while循環(huán)首先嘗試獲得一個連接,如果失敗,wait()函數(shù)被調(diào)用來等待需要的時間。后面會看到,Wait()函數(shù)會在另一個進程調(diào)用notify()或者notifyAll()時返回,或者等到時間流逝完畢。為了確定wait()是因為何種原因返回,我們用開始時間減去當前時間,檢查是否大于timeout。如果結果大于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)在有了一個連接。

        六、關閉

        大多數(shù)servlet引擎提供完整的關閉方法。數(shù)據(jù)庫連接池需要得到通知以正確地關閉所有的連接。DBConnectionManager負責協(xié)調(diào)關閉事件,但連接由各個連接池自己負責關閉。方法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向量以關閉所有的連接。

        DBConnetionManager的構造函數(shù)是私有函數(shù),以避免其他類創(chuàng)建其實例。

      private DBConnectionManager() {

      init();

        DBConnetionManager的客戶調(diào)用getInstance()方法來得到該類的單一實例的引用。

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

        連結池使用實例

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

        一、初始化

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

         drivers 以空格分開的jdbc驅(qū)動程序的列表

         logfile 日志文件的絕對路徑

        每個連接池中還使用另一些屬性。這些屬性以連接池的名字開頭:

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

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

         .user連接池的用戶名

         .password相關的密碼

        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在當前目錄下創(chuàng)建。在此情況下,一個系統(tǒng)錯誤被紀錄。

        方法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屬性分成單獨的driver串,并將每個驅(qū)動程序裝入java虛擬機。驅(qū)動程序的實例在JDBC 的DriverManager中注冊,并加入一個私有的向量drivers中。向量drivers用來關閉和注銷所有的驅(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結尾,則表示是一個連接池對象需要被實例化。創(chuàng)建的連接池對象保存在一個Hashtable實例變量中。連接池名字作為索引,連接池對象作為值。

        二、得到和返回連接

        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);
       }

        三、關閉

        最后,由一個release()方法,用來完好地關閉連接池。每個DBConnectionManager客戶必須調(diào)用getInstance()方法引用。有一個計數(shù)器跟蹤客戶的數(shù)量。方法release()在客戶關閉時調(diào)用,技術器減1。當最后一個客戶釋放,DBConnectionManager關閉所有的連接池。

      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驅(qū)動程序也被注銷。
        連結池的作用

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

        一、首先簡單介紹一下Servlet的生命周期:

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

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

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

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

        二、servlet中使用連接池的實例

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

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

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

        3. 在destroy()中,調(diào)用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();
       }

        本站是提供個人知識管理的網(wǎng)絡存儲空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點。請注意甄別內(nèi)容中的聯(lián)系方式、誘導購買等信息,謹防詐騙。如發(fā)現(xiàn)有害或侵權內(nèi)容,請點擊一鍵舉報。
        轉(zhuǎn)藏 分享 獻花(0

        0條評論

        發(fā)表

        請遵守用戶 評論公約

        類似文章 更多