最大的網(wǎng)站源碼資源下載站,
連結(jié)數(shù)據(jù)庫string url=”jdbc:inetdae:myserver:1433?language=us-english&sql7=true”
表示采用inetdae驅(qū)動(dòng)程序連接1433端口上的myserver數(shù)據(jù)庫服務(wù)器,選擇語言為美國英語,數(shù)據(jù)庫的版本是mssql server 7.0。class.forname(“”);
或class.forname(“”).newinstance();
然后,drivermanager創(chuàng)建一個(gè)特定的連接:connection connection=drivermanager.getconnection(url,login,password);
statement stmt=connection.createstatement();
statement具有各種方法(api),如executequery,execute等可以返回查詢的結(jié)果集。結(jié)果集是一個(gè)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://為顯示一些的信息打開一個(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://打開一個(gè)連接 
  connection connection = drivermanager.getconnection(url,login,password); 
  file://得到數(shù)據(jù)庫驅(qū)動(dòng)程序版本 
   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(); 
  } 
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; 
} 
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; 
} 
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; 
}
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; 
} 
public synchronized void freeconnection(connection con) { 
 // put the connection at the end of the vector 
 freeconnections.addelement(con); 
 checkedout--; 
 notifyall(); 
} 
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(); 
} 
private dbconnectionmanager() { 
init(); 
} 
static synchronized public dbconnectionmanager getinstance() { 
if (instance == null) { 
 instance = new dbconnectionmanager(); 
} 
clients++; 
return instance; 
} 
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); 
} 
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 
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); 
  } 
 } 
} 
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); 
  } 
 } 
} 
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); 
 } 
} 
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)程序也被注銷。
  連結(jié)池的作用
  現(xiàn)在我們結(jié)合dbconnetionmanager和dbconnectionpool類來講解servlet中連接池的使用: 
  一、首先簡單介紹一下servlet的生命周期: 
  servlet api定義的servlet生命周期如下: 
  1、 servlet 被創(chuàng)建然后初始化(init()方法)。 
  2、 為0個(gè)或多個(gè)客戶調(diào)用提供服務(wù)(service()方法)。 
  3、 servlet被銷毀,內(nèi)存被回收(destroy()方法)。 
  二、servlet中使用連接池的實(shí)例 
  使用連接池的servlet有三個(gè)階段的典型表現(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(); 
 } 
} 
新聞熱點(diǎn)
疑難解答
圖片精選