您的位置:首页 > 编程语言 > Java开发

数据库连接池 java 整理

2013-12-04 13:14 357 查看
package com.jcy.Achieve;
import java.sql.*;
import java.util.*;
public interface DatabaseAccessInterface {
public abstract void setName(String name);
public abstract void getName();
public abstract void executeSQL(String sqlStatement) throws SQLException;
public abstract void executeSQL(String[] sqlStatement) throws SQLException;
public abstract void executeSQL(String sqlStatement, Object parameters[]) throws SQLException;
public abstract void executeSQL(String sqlStatement, List parameters) throws SQLException;
public abstract void executeSQL(String[] sqlStatement, List parameters) throws SQLException;
public abstract Vector executeQuerySQL(String sqlStatement) throws SQLException;
public abstract Vector executeQuerySQL(String sqlStatement, Object parameters[]) throws SQLException;
public abstract Vector executeQuerySQL(String sqlStatement, List parameters) throws SQLException;
public abstract String getSequenceNum(String tableName) throws SQLException;
}
package com.jcy.Achieve;

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

import com.jcy.DBConnection.DBConnectionManager;

public class DatabaseAccessImpl implements DatabaseAccessInterface
{
// 可写入插入,删除,修改
public void executeSQL(String sqlStatement) throws SQLException
{
PreparedStatement statement = null;
Connection con = null;
DBConnectionManager connectionMan = DBConnectionManager.getInstance();// 得到唯一实例
// 得到连接
String name = "test";// 从上下文得到你要访问的数据库的名字
try
{

con = connectionMan.getConnection(name);
con.setAutoCommit(false);
statement = con.prepareStatement(sqlStatement);
statement.execute();
con.commit();
} catch (SQLException ex)
{
con.rollback();
ex.printStackTrace();
throw ex;
} catch (Exception ex)
{
con.rollback();
ex.printStackTrace();
} finally
{
try
{
statement.close();
} catch (SQLException ex)
{
ex.printStackTrace();
}
connectionMan.freeConnection(name, con);// 释放,但并未断开连接
}
// return;
}

// 设置预编译--增删改--
public void executeSQL(String sqlStatement, Object parameters[])
throws SQLException
{
PreparedStatement statement = null;
Connection con = null;
DBConnectionManager connectionMan = DBConnectionManager.getInstance();// 得到唯一实例
// 得到连接
String name = "test";// 从上下文得到你要访问的数据库的名字
try
{

con = connectionMan.getConnection(name);
con.setAutoCommit(false);
statement = con.prepareStatement(sqlStatement);
// 获取执行数据
if (parameters != null && parameters.length > 0)
{
for (int i = 0; i < parameters.length; i++)
{
statement.setObject(i + 1, parameters[i]);
}
}
statement.execute();
con.commit();
} catch (SQLException ex)
{
con.rollback();
ex.printStackTrace();
throw ex;
} catch (Exception ex)
{
con.rollback();
ex.printStackTrace();
} finally
{
try
{
statement.close();
} catch (SQLException ex)
{
ex.printStackTrace();
}
connectionMan.freeConnection(name, con);
}
System.out
.println("这个是	executeSQL(String sqlStatement, Object parameters[])");
// return;
}

public void executeSQL(String sqlStatement, List parameters)
throws SQLException
{
PreparedStatement statement = null;
Connection con = null;
DBConnectionManager connectionMan = DBConnectionManager.getInstance();// 得到唯一实例
// 得到连接
String name = "test";// 从上下文得到你要访问的数据库的名字
try
{
con = connectionMan.getConnection(name);
con.setAutoCommit(false);
statement = con.prepareStatement(sqlStatement);
// 获取执行数据
int listsize = parameters.size();
for (int i = 0; i < listsize; i++)
{
statement.setObject(i + 1, parameters.get(i));
}
statement.execute();
con.commit();
} catch (SQLException ex)
{
con.rollback();
ex.printStackTrace();
throw ex;
} catch (Exception ex)
{
con.rollback();
ex.printStackTrace();
} finally
{
try
{
statement.close();
} catch (SQLException ex)
{
ex.printStackTrace();
}
connectionMan.freeConnection(name, con);
}
System.out
.println("这个是	executeSQL(String sqlStatement, Object parameters[])");
// return;
}

public void executeSQL(String[] sqlStatement) throws SQLException
{
Connection con = null;
PreparedStatement statement = null;
if (sqlStatement == null || sqlStatement.length == 0)
{
throw new SQLException();
}
DBConnectionManager connectionMan = DBConnectionManager.getInstance();// 得到唯一实例
// 得到连接
String name = "test";// 从上下文得到你要访问的数据库的名字
try
{
con = connectionMan.getConnection(name);
con.setAutoCommit(false);
int slength = sqlStatement.length;// 事务中sql语句的个数
for (int i = 0; i < slength; i++)
{
statement = con.prepareStatement(sqlStatement[i]);
statement.execute();
}
con.commit();
} catch (SQLException ex)
{
con.rollback();
ex.printStackTrace();
throw ex;
} catch (Exception ex)
{
con.rollback();
ex.printStackTrace();
} finally
{
try
{
statement.close();
} catch (SQLException ex)
{
ex.printStackTrace();
}
connectionMan.freeConnection(name, con);
}
// return;
}

public void executeSQL(String[] sqlStatement, List parameters)
throws SQLException
{
Connection con = null;
PreparedStatement statement = null;
if (sqlStatement == null || sqlStatement.length == 0)
{
throw new SQLException();
}
DBConnectionManager connectionMan = DBConnectionManager.getInstance();// 得到唯一实例
// 得到连接
String name = "test";// 从上下文得到你要访问的数据库的名字
try
{

con = connectionMan.getConnection(name);
con.setAutoCommit(false);
int slength = sqlStatement.length;// 事务中sql语句的个数
for (int i = 0; i < slength; i++)
{
statement = con.prepareStatement(sqlStatement[i]);
if (parameters != null)
{
Object[] pm = (Object[]) parameters.get(i);
// 获取执行数据
int pmsize = 0;// 每条sql数据对应的参数个数
if (pm != null)
{
pmsize = pm.length;
}
for (int j = 0; j < pmsize; j++)
{
statement.setObject(j + 1, pm[j]);
}
}
statement.execute();
}
con.commit();
} catch (SQLException ex)
{
con.rollback();
ex.printStackTrace();
throw ex;
} catch (Exception ex)
{
con.rollback();
ex.printStackTrace();
} finally
{
try
{
statement.close();
} catch (SQLException ex)
{
ex.printStackTrace();
}
connectionMan.freeConnection(name, con);
}
// return;
}

public Vector executeQuerySQL(String sqlStatement) throws SQLException
{
Vector resultVector = new Vector();
Connection con = null;
PreparedStatement statement = null;
ResultSet rs = null;
DBConnectionManager connectionMan = DBConnectionManager.getInstance();// 得到唯一实例
// 得到连接
String name = "test";// 从上下文得到你要访问的数据库的名字
try
{

con = connectionMan.getConnection(name);
con.setAutoCommit(false);
statement = con.prepareStatement(sqlStatement); // 获取statement对象
statement.execute();
rs = statement.getResultSet(); // 获取查询记录集
HashMap rowItem;
for (; rs.next(); resultVector.add(rowItem))
{
rowItem = new HashMap();
int columnCount = rs.getMetaData().getColumnCount();
for (int i = 1; i <= columnCount; i++)
{
Object cell = rs.getObject(i);
if (cell == null)
{
cell = "";
} else if (cell instanceof Blob)
{
try
{
InputStreamReader in = new InputStreamReader(
((Blob) cell).getBinaryStream());
char bufferString[] = new char[5000];
int readCharCount = in.read(bufferString);
StringBuffer bolbStringBuffer = new StringBuffer("");
for (; readCharCount == 5000; readCharCount = in
.read(bufferString))
{
bolbStringBuffer.append(bufferString, 0,
readCharCount);
}
if (readCharCount != -1)
{
bolbStringBuffer.append(bufferString, 0,
readCharCount);
}
cell = bolbStringBuffer.toString();
in.close();
} catch (Exception ex)
{
ex.printStackTrace();
}
}
rowItem.put(rs.getMetaData().getColumnName(i), cell);
}
}
con.commit();
} catch (SQLException ex)
{
con.rollback();
ex.printStackTrace();
throw ex;
} catch (Exception ex)
{
con.rollback();
ex.printStackTrace();
} finally
{
try
{
rs.close();
} catch (SQLException ex)
{
ex.printStackTrace();
}
try
{
statement.close();
} catch (SQLException ex)
{
ex.printStackTrace();
}
connectionMan.freeConnection(name, con);
}
return resultVector;
}

public Vector executeQuerySQL(String sqlStatement, Object parameters[])
throws SQLException
{
Vector resultVector = new Vector();
Connection con = null;
PreparedStatement statement = null;
ResultSet rs = null;
DBConnectionManager connectionMan = DBConnectionManager.getInstance();// 得到唯一实例
// 得到连接
String name = "test";// 从上下文得到你要访问的数据库的名字
try
{

con = connectionMan.getConnection(name);
con.setAutoCommit(false);
statement = con.prepareStatement(sqlStatement); // 获取statement对象
// 获取查询参数
if (parameters != null && parameters.length > 0)
{
for (int i = 0; i < parameters.length; i++)
{
statement.setObject(i + 1, parameters[i]);
}
}
statement.execute();
rs = statement.getResultSet(); // 获取查询记录集
HashMap rowItem;
for (; rs.next(); resultVector.add(rowItem))
{
rowItem = new HashMap();
int columnCount = rs.getMetaData().getColumnCount();
for (int i = 1; i <= columnCount; i++)
{
Object cell = rs.getObject(i);
if (cell == null)
{
cell = "";
} else if (cell instanceof Blob)
{
try
{
InputStreamReader in = new InputStreamReader(
((Blob) cell).getBinaryStream());
char bufferString[] = new char[5000];
int readCharCount = in.read(bufferString);
StringBuffer bolbStringBuffer = new StringBuffer("");
for (; readCharCount == 5000; readCharCount = in
.read(bufferString))
{
bolbStringBuffer.append(bufferString, 0,
readCharCount);
}
if (readCharCount != -1)
{
bolbStringBuffer.append(bufferString, 0,
readCharCount);
}
cell = bolbStringBuffer.toString();
in.close();
} catch (Exception ex)
{
ex.printStackTrace();
}
}
rowItem.put(rs.getMetaData().getColumnName(i), cell);
}
}
con.commit();
} catch (SQLException ex)
{
con.rollback();
ex.printStackTrace();
throw ex;
} catch (Exception ex)
{
con.rollback();
ex.printStackTrace();
} finally
{
try
{
rs.close();
} catch (SQLException ex)
{
ex.printStackTrace();
}
try
{
statement.close();
} catch (SQLException ex)
{
ex.printStackTrace();
}
connectionMan.freeConnection(name, con);
}
return resultVector;
}

public Vector executeQuerySQL(String sqlStatement, List parameters)
throws SQLException
{
Vector resultVector = new Vector();
Connection con = null;
PreparedStatement statement = null;
ResultSet rs = null;
DBConnectionManager connectionMan = DBConnectionManager.getInstance();// 得到唯一实例
// 得到连接
String name = "test";// 从上下文得到你要访问的数据库的名字
try
{

con = connectionMan.getConnection(name);
con.setAutoCommit(false);
statement = con.prepareStatement(sqlStatement); // 获取statement对象
// 获取查询数据
int listsize = parameters.size();
for (int i = 0; i < listsize; i++)
{
statement.setObject(i + 1, parameters.get(i));
}
statement.execute();
rs = statement.getResultSet(); // 获取查询记录集
HashMap rowItem;
for (; rs.next(); resultVector.add(rowItem))
{
rowItem = new HashMap();
int columnCount = rs.getMetaData().getColumnCount();
for (int i = 1; i <= columnCount; i++)
{
Object cell = rs.getObject(i);
if (cell == null)
{
cell = "";
} else if (cell instanceof Blob)
{
try
{
InputStreamReader in = new InputStreamReader(
((Blob) cell).getBinaryStream());
char bufferString[] = new char[5000];
int readCharCount = in.read(bufferString);
StringBuffer bolbStringBuffer = new StringBuffer("");
for (; readCharCount == 5000; readCharCount = in
.read(bufferString))
{
bolbStringBuffer.append(bufferString, 0,
readCharCount);
}
if (readCharCount != -1)
{
bolbStringBuffer.append(bufferString, 0,
readCharCount);
}
cell = bolbStringBuffer.toString();
in.close();
} catch (Exception ex)
{
ex.printStackTrace();
}
}
rowItem.put(rs.getMetaData().getColumnName(i), cell);
}
}
con.commit();
} catch (SQLException ex)
{
con.rollback();
ex.printStackTrace();
throw ex;
} catch (Exception ex)
{
con.rollback();
ex.printStackTrace();
} finally
{
try
{
rs.close();
} catch (SQLException ex)
{
ex.printStackTrace();
}
try
{
statement.close();
} catch (SQLException ex)
{
ex.printStackTrace();
}
connectionMan.freeConnection(name, con);
}
return resultVector;
}

public String getSequenceNum(String tableName) throws SQLException
{
Connection con = null;
PreparedStatement statement = null;
ResultSet rs = null;
String squenceNumber = "";
String sequenceStatement = "select " + tableName
+ "_seq.nextval from dual";
DBConnectionManager connectionMan = DBConnectionManager.getInstance();// 得到唯一实例
// 得到连接
String name = "test";// 从上下文得到你要访问的数据库的名字
try
{

con = connectionMan.getConnection(name);
con.setAutoCommit(false);
statement = con.prepareStatement(sequenceStatement);
rs = statement.executeQuery();
rs.next();
squenceNumber = rs.getBigDecimal(1).toString();
con.commit();
} catch (SQLException ex)
{
con.rollback();
ex.printStackTrace();
throw ex;
} catch (Exception ex)
{
con.rollback();
ex.printStackTrace();
} finally
{
try
{
rs.close();
} catch (SQLException ex)
{
ex.printStackTrace();
}
try
{
statement.close();
} catch (SQLException ex)
{
ex.printStackTrace();
}
connectionMan.freeConnection(name, con);
}
return squenceNumber;
}

@Override
public void setName(String name)
{
// TODO Auto-generated method stub

}

@Override
public void getName()
{
// TODO Auto-generated method stub

}
}


<ds-config>
<pool>
<type>oracle</type>
<name>test</name>
<driver>oracle.jdbc.driver.OracleDriver</driver>
<url>jdbc:oracle:thin:@localhost:1521:ORCL</url>
<username>scott</username>
<password>tiger</password>
<maxconn>100</maxconn>
</pool>
</ds-config>


package com.jcy.Achieve;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Map;
import java.util.Vector;

public class Opreation
{

public void insertOne(DatabaseAccessImpl dai)
{
try
{
dai.executeSQL("insert into  studentdata values('100809','索尼','男',26)");
} catch (SQLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}

public void insertTwo(DatabaseAccessImpl dai)
{
//两个参数 1,预编译语句,2,条件(list)
ArrayList alist = new ArrayList();
alist.add("100805");
alist.add("Angle");
alist.add("女");
alist.add(4);
try
{
dai.executeSQL("insert into  studentdata values(?,?,?,?)",alist);
} catch (SQLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}

public void  upDate(DatabaseAccessImpl dai)
{
try
{
dai.executeSQL("update studentdata set stid='100808',stsex='男',stage=7 where stname='华硕'");
} catch (SQLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}

public void remove(DatabaseAccessImpl dai)
{
String sql = "delete from studentdata where stid='100809'";
try
{
dai.executeSQL(sql);
} catch (SQLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}

public void findAll(DatabaseAccessImpl dai)
{
Vector rs = null;
try
{
rs = dai.executeQuerySQL("select * from studentdata order by 1");
} catch (SQLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("学号"+"	"+"名字"+"	"+"性别"+"	"+"年龄");
for (Object object : rs) {
Map map = (Map) object;
System.out.println(map.get("STID")+"	"+map.get("STNAME")+"	"+map.get("STSEX")+"	"+map.get("STAGE"));
}
}

public void findTwoTable(DatabaseAccessImpl dai)
{
Vector rs = null;
try
{
rs = dai.executeQuerySQL("SELECT t.学号,b.* FROM TABLEONE t,TABLETWO b WHERE t.编号=b.编号 ");
} catch (SQLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("学号"+"		"+"编号"+"		"+"姓名"+"		"+"科目"+"		"+"成绩");
for(Object object : rs)
{
Map map = (Map) object;//对象向下转型
if(map instanceof Map)
{
System.out.println(map.get("学号")+"		"+map.get("编号")+"		"+map.get("姓名")+"		"+map.get("科目")+"		"+map.get("成绩"));
}
}
}
}


具体项目在这里下载 http://download.csdn.net/detail/jcy2sls/6654819 点击打开链接

以下是连接池具体实现方法,

package com.jcy.DBConnection;

public class DSConfigBean {
private String type = ""; 			// 数据库类型
private String name = ""; 			// 连接池名字
private String driver = ""; 		// 数据库驱动
private String url = ""; 			// 数据库 url
private String username = ""; 	// 用户名
private String password = ""; 		// 密码
private int maxconn  = 0; 			// 最大连接数

public String getDriver() {
return driver;
}

public void setDriver(String driver) {
this.driver = driver;
}

public int getMaxconn() {
return maxconn;
}

public void setMaxconn(int maxconn) {
this.maxconn = maxconn;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}

public String getType() {
return type;
}

public void setType(String type) {
this.type = type;
}

public String getUrl() {
return url;
}

public void setUrl(String url) {
this.url = url;
}

public String getUsername() {
return username;
}

public void setUsername(String username) {
this.username = username;
}

}


package com.jcy.DBConnection;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;

/**
* 一个配置文件操作类
*/
public class ParseDSConfig {
/**
* 读取 xml 配置文件
*/
public Vector readConfigInfo(String path) {
String rpath = this.getClass().getResource("").getPath().substring(1)
+ path;
Vector dsConfig = null;
FileInputStream fi = null;
try {
fi = new FileInputStream(rpath);// 读取路径文件
dsConfig = new Vector();
SAXBuilder sb = new SAXBuilder();
Document doc = sb.build(fi);
Element root = doc.getRootElement();
List pools = root.getChildren();
Element pool = null;
Iterator allPool = pools.iterator();
while (allPool.hasNext()) {
pool=(Element)allPool.next();
DSConfigBean dscBean=new DSConfigBean();
dscBean.setType(pool.getChild("type").getText());
dscBean.setName(pool.getChild("name").getText());
System.out.println(dscBean.getName());
dscBean.setDriver(pool.getChild("driver").getText());
dscBean.setUrl(pool.getChild("url").getText());
dscBean.setUsername(pool.getChild("username").getText());
dscBean.setPassword(pool.getChild("password").getText());
dscBean.setMaxconn(Integer.parseInt(pool.getChild("maxconn").getText()));
dsConfig.add(dscBean);

}

} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JDOMException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

finally {
try {
fi.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

return dsConfig;
}

}


package com.jcy.DBConnection;

import java.sql.Connection;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Vector;

/**
* 数据库管理类
* 一个连接池管理类
* 用于对多个连接池对象的管理
* ① 装载并注册特定数据库的 JDBC 驱动程序
* ② 根据属性文件给定的信息,创建连接池对象
* ③ 为方便管理多个连接池对象,为每一个连接池对象取一个名字,实现连接池名字与其实例之间的映射
* ④ 跟踪客户使用连接情况,以便需要是关闭连接释放资源。连接池管理类的引入主要是为了方便对多个连接池的使用和管理,
* 	如系统需要连接不同的数据库,或连接相同的数据库但由于 安全 性问题,需要不同的用户使用不同的名称和密码
* */
public class DBConnectionManager {
static private DBConnectionManager instance; // 唯一数据库连接池管理实例类
static private int clients; // 客户连接数
private Vector drivers = new Vector(); // 驱动信息
private Hashtable pools = new Hashtable(); // 连接池

/**
* 实例化管理类
*/
public DBConnectionManager() {
// TODO Auto-generated constructor stub
this.init();
}

/**
* 得到唯一实例管理类
* @return
*/
static synchronized public DBConnectionManager getInstance() {
if (instance == null) {
instance = new DBConnectionManager();
}
return instance;

}

/**
* 释放连接
* @param name
* @param con
*/
public void freeConnection(String name, Connection con) {
DBConnectionPool pool = (DBConnectionPool) pools.get(name);// 根据关键名字得到连接池
if (pool != null)
pool.freeConnection(con);// 释放连接
}

/**
* 得到一个连接根据连接池的名字 name
* @param name
* @return
*/
public Connection getConnection(String name) {
DBConnectionPool pool = null;
Connection con = null;
pool = (DBConnectionPool) pools.get(name);// 从名字中获取连接池
if(pool==null)
{
System.out.println("从名字中获取连接池失败");
}
con = pool.getConnection();// 从选定的连接池中获得连接
if (con != null)
System.out.println(" 得到连接。。。 ");
return con;
}

/**
* 得到一个连接,根据连接池的名字和等待时间
* @param name
* @param time
* @return
*/
public Connection getConnection(String name, long timeout) {
DBConnectionPool pool = null;
Connection con = null;
pool = (DBConnectionPool) pools.get(name);// 从名字中获取连接池
con = pool.getConnection(timeout);// 从选定的连接池中获得连接
System.out.println(" 得到连接。。。 ");
return con;
}

/**
* 释放所有连接
*/
public synchronized void release() {
Enumeration allpools = pools.elements();
while (allpools.hasMoreElements()) {
DBConnectionPool pool = (DBConnectionPool) allpools.nextElement();
if (pool != null)
pool.release();
}
pools.clear();
}

/**
* 创建连接池
* @param props
*/
private void createPools(DSConfigBean dsb) {
DBConnectionPool dbpool = new DBConnectionPool();
dbpool.setName(dsb.getName());
dbpool.setDriver(dsb.getDriver());
dbpool.setUrl(dsb.getUrl());
dbpool.setUser(dsb.getUsername());
dbpool.setPassword(dsb.getPassword());
dbpool.setMaxConn(dsb.getMaxconn());
System.out.println("ioio:" + dsb.getMaxconn());
pools.put(dsb.getName(), dbpool);
}

/**
* 初始化连接池的参数
*/
private void init() {
// 加载驱动程序
this.loadDrivers();
// 创建连接池
Iterator alldriver = drivers.iterator();
while (alldriver.hasNext()) {
this.createPools((DSConfigBean) alldriver.next());
System.out.println(" 创建连接池。。。 ");

}
System.out.println(" 创建连接池完毕。。。 ");
}

/**
* 加载驱动程序
* @param props
*/
private void loadDrivers() {
ParseDSConfig pd = new ParseDSConfig();
// 读取数据库配置文件
drivers = pd.readConfigInfo("ds.config.xml");
System.out.println(" 加载驱动程序。。。 ");
}
}


package com.jcy.DBConnection;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Time;
import java.util.ArrayList;
import java.util.Iterator;

/**
* 连接池类
* 连接池类是对某一 数据库 所有连接的"缓冲池"
* 主要实现以下功能:
* ① 从连接池获取或创建可用连接
* ② 使用完毕之后,把连接返还给连接池
* ③ 在系统关闭前,断开所有连接并释放连接占用的系统资源
* ④ 还能够处理无效连接(原来登记为可用的连接,由于某种原因不再可用,如超时,通讯问题),
*    并能够限制连接池中的连接总数不低于某个预定值和不超过某个预定值
* (5) 当多数据库时 , 且数据库是动态增加的话 , 将会加到配置文件中
* */
public class DBConnectionPool {
private Connection con = null;
private int inUsed = 0; // 使用的连接数
private ArrayList freeConnections = new ArrayList();// 容器,空闲连接
private int minConn; // 最小连接数
private int maxConn; // 最大连接
private String name; // 连接池名字
private String password; // 密码
private String url; // 数据库连接地址
private String driver; // 驱动
private String user; // 用户名
public Time timer; // 定时

/**
*
*/
public DBConnectionPool() {
// TODO Auto-generated constructor stub
}

/**
* 创建连接池
* @param driver
* @param name
* @param URL
* @param user
* @param password
* @param maxConn
*/
public DBConnectionPool(String name, String driver, String URL,
String user, String password, int maxConn) {
this.name = name;
this.driver = driver;
this.url = URL;
this.user = user;
this.password = password;
this.maxConn = maxConn;
}

/**
* 用完,释放连接
* @param con
*/
public synchronized void freeConnection(Connection con) {
this.freeConnections.add(con);// 添加到空闲连接的末尾
this.inUsed--;
}

/**
* timeout  根据 timeout 得到连接
* @param timeout
* @return
*/
public synchronized Connection getConnection(long timeout) {
Connection con = null;
if (this.freeConnections.size() > 0) {
con = (Connection) this.freeConnections.get(0);
if (con == null)
con = getConnection(timeout); // 继续获得连接
} else {
con = newConnection(); // 新建连接
}
if (this.maxConn == 0 || this.maxConn < this.inUsed) {
con = null;// 达到最大连接数,暂时不能获得连接了。
}
if (con != null) {
this.inUsed++;
}
return con;
}

/**
*
* 从连接池里得到连接
* @return
*/
public synchronized Connection getConnection() {
Connection con = null;
if (this.freeConnections.size() > 0) {
con = (Connection) this.freeConnections.get(0);
this.freeConnections.remove(0);// 如果连接分配出去了,就从空闲连接里删除
if (con == null)
con = getConnection(); // 继续获得连接
} else {
con = newConnection(); // 新建连接
}
if (this.maxConn == 0 || this.maxConn < this.inUsed) {
con = null;// 等待 超过最大连接时
}
if (con != null) {
this.inUsed++;
System.out.println(" 得到  " + this.name + "  的连接,现有 " + inUsed
+ " 个连接在使用 !");
}
return con;
}

/**
* 释放全部连接
*
*/
public synchronized void release() {
Iterator allConns = this.freeConnections.iterator();
while (allConns.hasNext()) {
Connection con = (Connection) allConns.next();
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}

}
this.freeConnections.clear();

}

/**
* 创建新连接
* @return
*/
private Connection newConnection() {
try {
Class.forName(driver);
con = DriverManager.getConnection(url, user, password);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return con;

}

/**
* 定时处理函数
*/
public synchronized void TimerEvent() {
// 暂时还没有实现以后会加上的
}

public String getDriver() {
return driver;
}

public void setDriver(String driver) {
this.driver = driver;
}

public int getMaxConn() {
return maxConn;
}

public void setMaxConn(int maxConn) {
this.maxConn = maxConn;
}

public int getMinConn() {
return minConn;
}

public void setMinConn(int minConn) {
this.minConn = minConn;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}

public String getUrl() {
return url;
}

public void setUrl(String url) {
this.url = url;
}

public String getUser() {
return user;
}

public void setUser(String user) {
this.user = user;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: