最大的网站源码资源下载站,
连结数据库string url=”jdbc:inetdae:myserver:1433?language=us-english&sql7=true”
表示采用inetdae驱动程序连接1433端口上的myserver数据库服务器,选择语言为美国英语,数据库的版本是mssql server 7.0。class.forname(“”);
或class.forname(“”).newinstance();
然后,drivermanager创建一个特定的连接:connection connection=drivermanager.getconnection(url,login,password);
statement stmt=connection.createstatement();
statement具有各种方法(api),如executequery,execute等可以返回查询的结果集。结果集是一个resultset对象。具体的可以通过jdbc开发文档查看。可以sun的站点上下载import java.sql.*; // 输入jdbc package
string url = "jdbc:inetdae:myserver:1433";// 主机名和端口
string login = "user";// 登录名
string password = "";// 密码
try {
drivermanager.setlogstream(system.out); file://为显示一些的信息打开一个流
file://调用驱动程序,其名字为com.inet.tds.tdsdriver
file://class.forname("com.inet.tds.tdsdriver");
file://设置超时
drivermanager.setlogintimeout(10);
file://打开一个连接
connection connection = drivermanager.getconnection(url,login,password);
file://得到数据库驱动程序版本
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://创建statement
statement st = connection.createstatement();
file://执行查询
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();
}
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());
}
}
}
当所有连接池关闭,所有jdbc驱动程序也被注销。
连结池的作用
现在我们结合dbconnetionmanager和dbconnectionpool类来讲解servlet中连接池的使用:
一、首先简单介绍一下servlet的生命周期:
servlet api定义的servlet生命周期如下:
1、 servlet 被创建然后初始化(init()方法)。
2、 为0个或多个客户调用提供服务(service()方法)。
3、 servlet被销毁,内存被回收(destroy()方法)。
二、servlet中使用连接池的实例
使用连接池的servlet有三个阶段的典型表现是:
1. 在init()中,调用dbconnectionmanager.getinstance()然后将返回的引用保存在实例变量中。
2. 在sevice()中,调用getconnection(),执行一系列数据库操作,然后调用freeconnection()归还连接。
3. 在destroy()中,调用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();
}
}
新闻热点
疑难解答