欧美性猛交XXXX免费看蜜桃,成人网18免费韩国,亚洲国产成人精品区综合,欧美日韩一区二区三区高清不卡,亚洲综合一区二区精品久久

打開(kāi)APP
userphoto
未登錄

開(kāi)通VIP,暢享免費電子書(shū)等14項超值服

開(kāi)通VIP
Servlet開(kāi)發(fā)中JDBC的高級應用

  連結數據庫

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

  Jdbc::[node]/[database]

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

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

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

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

Class.forName(“”);

  或  

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

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

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

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

Statement stmt=connection.createStatement(); 

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

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

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

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

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

   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://創(chuàng )建Statement

  Statement st = connection.createStatement();

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

  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://關(guān)閉對象
  st.close();
    connection.close();
  } catch(Exception e) {
    e.printStackTrace();
  } 
  建立連結池

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

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

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

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

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

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

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

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

  1、 調用和注冊所有的jdbc驅動(dòng)程序;

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

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

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

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

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

  將所有的參數保存在實(shí)例變量中。

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

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

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

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

  如果沒(méi)有可用的連接,該方法檢查是否最大連接數被設置為0表示無(wú)限連接數,或者達到了最大連接數。如果可以創(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ù)名,密碼等參數創(chuàng )建一個(gè)連接。

  第二個(gè)getConnection()方法帶有一個(gè)超時(shí)參數 timeout,當該參數指定的毫秒數表示客戶(hù)愿意為一個(gè)連接等待的時(shí)間。這個(gè)方法調用前一個(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初始化當前的時(shí)間。一個(gè)while循環(huán)首先嘗試獲得一個(gè)連接,如果失敗,wait()函數被調用來(lái)等待需要的時(shí)間。后面會(huì )看到,Wait()函數會(huì )在另一個(gè)進(jìn)程調用notify()或者notifyAll()時(shí)返回,或者等到時(shí)間流逝完畢。為了確定wait()是因為何種原因返回,我們用開(kāi)始時(shí)間減去當前時(shí)間,檢查是否大于timeout。如果結果大于timeout,返回null,否則,在此調用getConnection()函數。

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

  DBConnectionPool類(lèi)中有一個(gè)freeConnection方法以返回的連接作為參數,將連接返回連接池。

public synchronized void freeConnection(Connection con) {
 // Put the connection at the end of the Vector
 freeConnections.addElement(con);
 checkedOut--;
 notifyAll();

  連接被加在freeConnections向量的最后,占用的連接數減1,調用notifyAll()函數通知其他等待的客戶(hù)現在有了一個(gè)連接。

  六、關(guān)閉

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

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

private DBConnectionManager() {

init();

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

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

  連結池使用實(shí)例

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

  一、初始化

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

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

   logfile 日志文件的絕對路徑

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

   .url數據庫的JDBC URL

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

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

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

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

  下面是windows平臺下的一個(gè)db.properties文件的例子。有一個(gè)InstantDB連接池和一個(gè)通過(guò)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 

  注意,反斜線(xiàn)在windows平臺下必須雙寫(xiě)。

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

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

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

  然后,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);
  }
 }

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

  二、得到和返回連接

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

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ù)必須調用getInstance()方法引用。有一個(gè)計數器跟蹤客戶(hù)的數量。方法release()在客戶(hù)關(guān)閉時(shí)調用,技術(shù)器減1。當最后一個(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());
  }
 }

  當所有連接池關(guān)閉,所有jdbc驅動(dòng)程序也被注銷(xiāo)。
  連結池的作用

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

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

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

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

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

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

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

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

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

  2. 在sevice()中,調用getConnection(),執行一系列數據庫操作,然后調用freeConnection()歸還連接。

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

本站僅提供存儲服務(wù),所有內容均由用戶(hù)發(fā)布,如發(fā)現有害或侵權內容,請點(diǎn)擊舉報。
打開(kāi)APP,閱讀全文并永久保存 查看更多類(lèi)似文章
猜你喜歡
類(lèi)似文章
Java jdbc數據庫連接池總結!
使用 JDBC Driver
JDBC---將數據庫連接信息放置配置文件中
JDBC這個(gè)問(wèn)題,問(wèn)的小伙伴一臉懵逼
聊聊JDBC是如何破壞雙親委派機制的
基于JDBC的數據庫連接池技術(shù)研究與應用
更多類(lèi)似文章 >>
生活服務(wù)
分享 收藏 導長(cháng)圖 關(guān)注 下載文章
綁定賬號成功
后續可登錄賬號暢享VIP特權!
如果VIP功能使用有故障,
可點(diǎn)擊這里聯(lián)系客服!

聯(lián)系客服

欧美性猛交XXXX免费看蜜桃,成人网18免费韩国,亚洲国产成人精品区综合,欧美日韩一区二区三区高清不卡,亚洲综合一区二区精品久久