首 页 网络编程
网页制作 图形图象 操作系统 冲浪宝典
软件教学 认证考试

网络安全 网络办公 行业资讯 评测对比
您当前位置:站长天空 -> 软件教学-> 文件管理
java连接sqlserver实例-JSP教程,Java技巧及代码
作者:网友供稿 点击:697
推荐
西部数码-全国虚拟主机10强!20余项虚拟主机管理功能,全国领先!第6代双线路虚拟主机,南北访问畅通无阻!可在线rar解压,自动数据恢复设置虚拟目录等.免费赠送访问统计,企业邮局.Cn域名注册10元/年,自助建站480元起,免费试用7天,满意再付款!P4主机租用799元/月.月付免压金
站内搜索
文章页数:[1] 
package sanpai.db;

import java.io.*;
import java.sql.*;
import java.util.*;
import java.util.date;

/**
* this class is a singleton that provides access to one or many
* connection pools defined in a property file. a client gets
* access to the single instance through the static getinstance()
* method and can then check-out and check-in connections from a pool.
* when the client shuts down it should call the release() method
* to close all open connections and do other clean up.
*/
public class dbconnectionmanager {
static private dbconnectionmanager instance; // the single instance
static private int clients;

private vector drivers = new vector();
private printwriter log;
private hashtable pools = new hashtable();

/**
* this inner class represents a connection pool. it creates new
* connections on demand, up to a max number if specified.
* it also makes sure a connection is still open before it is
* returned to a client.
*/
class dbconnectionpool {
private int checkedout;
private vector freeconnections = new vector();
private int maxconn;
private string name;
private string password;
private string url;
private string user;

/**
* creates new connection pool.
*
* @param name the pool name
* @param url the jdbc url for the database
* @param user the database user, or null
* @param password the database user password, or null
* @param maxconn the maximal number of connections, or 0
* for no limit
*/
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;
}

/**
* checks in a connection to the pool. notify other threads that
* may be waiting for a connection.
*
* @param con the connection to check in
*/
public synchronized void freeconnection(connection con) {
// put the connection at the end of the vector
freeconnections.addelement(con);
checkedout--;
notifyall();
}

/**
* checks out a connection from the pool. if no free connection
* is available, a new connection is created unless the max
* number of connections has been reached. if a free connection
* has been closed by the database, its removed from the pool
* and this method is called again recursively.
*/
public synchronized connection getconnection()throws sqlexception {
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;
}

/**
* checks out a connection from the pool. if no free connection
* is available, a new connection is created unless the max
* number of connections has been reached. if a free connection
* has been closed by the database, its removed from the pool
* and this method is called again recursively.
* <p>
* if no connection is available and the max number has been
* reached, this method waits the specified time for one to be
* checked in.
*
* @param timeout the timeout value in milliseconds
*/
public synchronized connection getconnection(long timeout) throws sqlexception {
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;
}

/**
* closes all available connections.
*/
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, "cant close connection for pool " + name);
}
}
freeconnections.removeallelements();
}

/**
* creates a new connection, using a userid and password
* if specified.
*/
private connection newconnection() throws sqlexception {
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, "cant create a new connection for " + url);
throw e;
}
return con;
}
}
/**
* a private constructor since this is a singleton
*/
private dbconnectionmanager() {
init();
}
/**
* creates instances of dbconnectionpool based on the properties.
* a dbconnectionpool can be defined with the following properties:
* <pre>
* &lt;poolname&gt;.url the jdbc url for the database
* &lt;poolname&gt;.user a database user (optional)
* &lt;poolname&gt;.password a database user password (if user specified)
* &lt;poolname&gt;.maxconn the maximal number of connections (optional)
* </pre>
*
* @param props the connection pool properties
*/
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);
}
}
}
/**
* returns a connection to the named pool.
*
* @param name the pool name as defined in the properties file
* @param con the connection
*/
public void freeconnection(string name, connection con) {
dbconnectionpool pool = (dbconnectionpool) pools.get(name);
if (pool != null) {
pool.freeconnection(con);
}
}
/**
* returns an open connection. if no one is available, and the max
* number of connections has not been reached, a new connection is
* created.
*
* @param name the pool name as defined in the properties file
* @return connection the connection or null
*/
public connection getconnection(string name) throws sqlexception {
dbconnectionpool pool = (dbconnectionpool) pools.get(name);
if (pool != null) {
return pool.getconnection();
}
return null;
}
/**
* returns an open connection. if no one is available, and the max
* number of connections has not been reached, a new connection is
* created. if the max number has been reached, waits until one
* is available or the specified time has elapsed.
*
* @param name the pool name as defined in the properties file
* @param time the number of milliseconds to wait
* @return connection the connection or null
*/
public connection getconnection(string name, long time) throws sqlexception {
dbconnectionpool pool = (dbconnectionpool) pools.get(name);
if (pool != null) {
return pool.getconnection(time);
}
return null;
}
/**
* returns the single instance, creating one if its the
* first time this method is called.
*
* @return dbconnectionmanager the single instance.
*/
static synchronized public dbconnectionmanager getinstance() {
if (instance == null) {
instance = new dbconnectionmanager();
}
clients++;
return instance;
}
/**
* loads properties and initializes the instance with its values.
*/
private void init() {
inputstream is = getclass().getresourceasstream("/db.properties");
properties dbprops = new properties();
try {
dbprops.load(is);
}
catch (exception e) {
system.err.println("cant 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("cant open the log file: " + logfile);
log = new printwriter(system.err);
}
loaddrivers(dbprops);
createpools(dbprops);
}
/**
* loads and registers all jdbc drivers. this is done by the
* dbconnectionmanager, as opposed to the dbconnectionpool,
* since many pools may share the same driver.
*
* @param props the connection pool properties
*/
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("cant register jdbc driver: " +
driverclassname + ", exception: " + e);
}
}
}
/**
* writes a message to the log file.
*/
private void log(string msg) {
log.println(new date() + ": " + msg);
}
/**
* writes a message with an exception to the log file.
*/
private void log(throwable e, string msg) {
log.println(new date() + ": " + msg);
e.printstacktrace(log);
}
/**
* closes all open connections and deregisters all drivers.
*/
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, "cant deregister jdbc driver: " + driver.getclass().getname());
}
}
}
/**
* release all resources when this object is destroyed.
*/
public void finalize() {
release();
}}


文章整理:站长天空 网址:http://www.z6688.com/
以上信息与文章正文是不可分割的一部分,如果您要转载本文章,请保留以上信息,谢谢!

文章页数:[1] 


放大字体显示 缩小字体显示 打印文章 推荐给朋友
热门文章
·C#:ListBox的2个常用方法Add,Clear与Items的2个属性-.NET教程,C#语言
·java连接sqlserver实例-JSP教程,Java技巧及代码
·Hibernate下数据批量处理解决方案-JSP教程,数据库相关
·一种基于pwm的电压输出dac电路设计
·delegate 与 多线程-.NET教程,算法/线程
·java Logging API 使用-JSP教程,Java技巧及代码
·ORACLE中LOB字段的使用和维护-ASP教程,数据库相关
·ups功率因数越大越好吗
·.NET三层经典架构PetShop3.0分析连载一-.NET教程,.NET Framework
·ASP后门之终极伪装-ASP教程,ASP基础
最新文章
·windows vista系统隐藏的12个网络工具_windows vista
·网站赚钱应如何选择网站联盟?_网赚技巧
·建站一级攻略 从看完之后就开始_站长心得
·论坛建设9大定律和经验分享_站长心得
·dreamweaver制作复杂交换图像_dreamweaver教程
·让你google广告90%不是公益广告的方法_google推广
·ppc 广告与转换率息息相关_google推广
·中国个人网站——新经济中的非主流1_站长心得
·blog设计的7个趋势_站长心得
·2005岁末blog程序大评点_站长心得
相关主题
  • java连接各种数据库的实例_java认证
  • Java连接SQL Server 2000-JSP教程,Java技巧及代码
  • Java连接Sybase数据库-JSP教程,数据库相关
  • JAVA连接数据库不用设数据源问题-JSP教程,数据库相关
  • java连接MySql数据库!-JSP教程,数据库相关
  • 西部数码虚拟主机

    友情链接
    CNNIC 西部数码
    万网 自助建站
    虚拟主机 asp空间
    域名注册 域名
    域名申请 主页空间
    论坛空间 网站空间
    国际域名 虚拟空间
    空间租用 DDOS防火墙
    成都主机托管 四川主机托管
    主机租用 服务器租用
    网站目录 自助建站
    虚拟主机 网址大全
    软件下载
    自助链接
    虚拟主机资讯 特价虚拟主机
    版权申明:本站文章均来自网络,如有侵权,请联系我们,我们收到后立即删除,谢谢!
    关于我们:站长天空:专业提供最新的站长资讯、在线教程、虚拟主机权威评测、虚拟主机性能对比、网站制作教程,开发教程,站长工具。包括网页制作教程、冲浪宝典、编程参考、操作系统、软件教学、行业动态等。
    特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有。
    发表评论 打印  刷新     关闭