package com.hujunbing.database;
/*
数据库连接池
南华大学计算机 胡军兵
CSDN lanbingg
***********说明*****************
本连接池只支持一个数据库,即一个连接池(感觉多连接池没必要)
首先写配置文件,配置文件应放在CLASSPATH中.
连接池配置文件范例:
logfile=e:\\log.txt
driver=com.mysql.jdbc.Driver
max=100
normal=10
user=root
password=139741
url=jdbc:mysql://localhost/shop
连接池调用范例:
DBPool pool;
pool =DBPool.getInstance();
con=pool.getConnection();
pool.freeConnection(con);
pool.release();
***********模块说明**************
getInstance()返回POOL唯一实例,第一次调用时将执行构造函数
构造函数Pool()调用驱动装载loadDrivers()函数;连接池创建createPool()函数
loadDrivers()装载驱动
createPool()建连接池
getConnection()返回一个连接实例
getConnection(long time)添加时间限制
freeConnection(Connection con)将con连接实例返回到连接池
getFree()返回空闲连接数
getActive()返回当前使用的连接数
*/
import java.io.*;
import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Date;
public class DBPool {
// //////////////////////连接池全局变量及监视变量///////////////
private static DBPool instance = null; // 定义唯一实例
private static Driver driver = null;// 驱动变量
private static Vector freeConnections = new Vector();// 空闲连接容器
private static PrintWriter log;// 日志记录变量
private static int max = 1000;// 最大连接数,0表示不限制最大连接
private static int normal = 10;// 保持连接数
private static int free = 0;// 空闲的连接数
private static int active = 0;// 活动的连接数
// 数据库连接参数
private static String password, url, user, driverName;
// 返回唯一实例
static synchronized public DBPool getInstance() {
if (instance == null) {
instance = new DBPool();
}
return instance;
}
// 将构造函数私有,不允许外界访问
private DBPool() {
init();// 初始化连接参数,日志
loadDrivers(driverName);
createPool();
}
// 初始化,读取属性设置文件
private void init() {
InputStream is = getClass().getResourceAsStream("db.properties");
Properties dbProps = new Properties();
try {
dbProps.load(is);
} catch (Exception e) {
System.err
.println("不能读取属性文件." + "请确保db.properties在CLASSPATH指定的路径中");
}
String logFile = dbProps.getProperty("logfile");
try {
// /初始化属性参数
driverName = dbProps.getProperty("driver");
url = dbProps.getProperty("url");
user = dbProps.getProperty("user");
password = dbProps.getProperty("password");
String maxNum = dbProps.getProperty("max");
String normalNum = dbProps.getProperty("normal");
max = Integer.parseInt(maxNum);
normal = Integer.parseInt(normalNum);
} catch (Exception e) {
System.err.println("初始化连接池参数出错,请检查配置文件");
}
System.out.println("the logFile is :" + logFile);
try {
log = new PrintWriter(new FileWriter(logFile, true), true);
// 写入日志
log("/***********************************/");
log("连接池创建开始");
log("driver:" + driverName);
log("url:" + url);
log("最大连接数:" + String.valueOf(max));
log("保持连接数:" + String.valueOf(normal));
} catch (IOException e) {
System.out.println("无法打开日志文件:" + logFile);
log = new PrintWriter(System.err);
}
}
// 装载和注册所有JDBC驱动程序
private void loadDrivers(String dri) {
String driverClassName = dri;
try {
driver = (Driver) Class.forName(driverClassName).newInstance();
DriverManager.registerDriver(driver);
log("成功注册JDBC驱动程序" + driverClassName);
} catch (Exception e) {
log("无法注册JDBC驱动程序:" + driverClassName + ",错误:" + e);
}
}
// 创建连接池
private void createPool() {
// 创制连接池,初始normalConn个连接
for (int i = 0; i < normal; i++) {
Connection c = newConnection();
if (c != null) {
freeConnections.addElement(c);// 空闲连接加入容器中
free++;// 空闲连接加1
}
}
}
// 获得一个可用的连接,如果没有则创建一个连接,且小于最大连接限制
public synchronized Connection getConnection() {
Connection con = null;
if (freeConnections.size() > 0) { // 还有空闲的连接
free--;
con = (Connection) freeConnections.firstElement();
freeConnections.removeElementAt(0);
try {
if (con.isClosed()) {
log("从连接池删除一个无效连接");
con = getConnection();
}
} catch (SQLException e) {
log("从连接池删除一个无效连接");
con = getConnection();
}
}
else if (max == 0 || active < max) { // 没有空闲连接且当前连接小于最大允许值,最大值为0则不限制
con = newConnection();
}
// 超过最大连接
else {
log("警告:当前连接超过最大连接数");
}
if (con != null) { // 活动连接数加1
active++;
}
return con;
}
// 获得一个连接,有时间限制
public 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) {
return null; // 超时返回
}
}
return con;
}
// 创建一个新连接
private Connection newConnection() {
Connection con = null;
try {
if (user == null) { // 用户,密码都为空
con = DriverManager.getConnection(url);
log("新建一个连接");
} else {
con = DriverManager.getConnection(url, user, password);
log("新建一个连接");
}
} catch (SQLException e) {
log("无法创建这个URL的连接" + url);
return null;
}
return con;
}
// 将连接对象返回给连接池
public synchronized void freeConnection(Connection con) {
try {
if(!con.isClosed())//连接有效
{
freeConnections.addElement(con);
free++;
active--;
notifyAll();
log("释放一个连接");
}
} catch (SQLException e) {
log("释放连接出错");
e.printStackTrace();
}
}
private void log(String msg) {
Date date = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
String time = dateFormat.format(date);
log.println(time + ": " + msg);
}
public void log(Throwable e, String msg) {
Date date = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
String time = dateFormat.format(date);
log.println(time + ": " + msg);
e.printStackTrace();
}
// 返回空闲连接数
public int getFree() {
return free;
}
// 返回活动的连接数
public int getActive() {
return active;
}
// 返回最大连接数
public int getMax() {
return max;
}
// 返回保持连接数
public int getNormal() {
return normal;
}
// 关闭所有连接,撤销驱动注册
public synchronized void release() {
log("开始关闭连接池");
// /关闭连接
Enumeration allConnections = freeConnections.elements();
while (allConnections.hasMoreElements()) {
Connection con = (Connection) allConnections.nextElement();
try {
con.close();
free--;
} catch (SQLException e) {
log("无法关闭连接池中的连接");
}
}
freeConnections.removeAllElements();
active = 0;
// 撤销驱动
try {
DriverManager.deregisterDriver(driver);
log("撤销JDBC驱动程序 " + driver.getClass().getName());
} catch (SQLException e) {
log("无法撤销JDBC驱动程序的注册:" + driver.getClass().getName());
}
instance=null;
log("/***********************************/");
}
}
没有合适的资源?快使用搜索试试~ 我知道了~
java数据库连接池(第二次修改,绝对好)
共3个文件
java:1个
properties:1个
class:1个
5星 · 超过95%的资源 需积分: 10 26 下载量 159 浏览量
2007-12-19
11:39:05
上传
评论
收藏 7KB RAR 举报
温馨提示
这个连接池只有一个类和一个配置文件,使用时只要写一下配置文件就可以,非常不错.自己写的,自我感觉比网上那个DBConnectionMannager结构清晰,也好用. 本类可以监视连接,有日志写入.哪位大侠再修改下,添加连接监控,自动管理就更好了.
资源推荐
资源详情
资源评论
收起资源包目录
DBPool.rar (3个子文件)
com
hujunbing
database
db.properties 131B
DBPool.class 7KB
DBPool.java 7KB
共 3 条
- 1
资源评论
- zhaodove2512013-10-15新手上路挺实用的
- wangfeiwoyun2012-10-15很简单,只能当一般般的学习
Bing_GoGo
- 粉丝: 27
- 资源: 8
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功