JDBC以及相关技术学习(九)----简单的连接池实现
来源:互联网 发布:淘宝联盟佣金神器 编辑:程序博客网 时间:2024/05/29 07:28
连接池:由于数据库的交互过程,主要时间都花在创建连接,那么有一种解决这种问题的情况,就是先创建一批连接,然后放在一个集合中,取连接的时候直接取出,释放连接的时候,不直接释放,而是将Connection对象直接放回集合,这样可以节省大量创建连接的时间。
public class MyDataSource implements DataSource {
private static String url = "jdbc:sqlserver://localhost:1433;DatabaseName=JDBCTEST";
private static String user = "sa";
private static String password = "password";
LinkedList<Connection> connectionsPool = new LinkedList<Connection>();//创建一个保存连接的集合
private static int intCount = 5;//首次创建连接的个数
private static int maxCount = 10;//最大创建连接的个数
private int currentCount = 0;//当前连接的个数
static{
try {
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");//注册驱动类
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public MyDataSource(){
for(int i = 0; i<intCount;i++){//先创建一部分,然后放在集合中
try {
this.connectionsPool.addLast(this.createConnection());
this.currentCount++;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private Connection createConnection() throws SQLException{//创建的方法
return DriverManager.getConnection(url, user, password);
}
public Connection GetConnection() throws SQLException
{
synchronized(connectionsPool){//获取连接时,先加锁,然后从连接池里取连接
if(this.connectionsPool.size()>0)
return connectionsPool.removeFirst();
if(this.currentCount<maxCount){
this.currentCount++;
return this.createConnection();//如果没有超过最大连接,则生成一个新的连接
}
throw new SQLException("链接已经没有了");
}
}
public void free(Connection conn){//释放连接时,将Connection放回连接池
this.connectionsPool.addLast(conn);
}
}
- JDBC以及相关技术学习(九)----简单的连接池实现
- JDBC以及相关技术学习(二)----把JDBC获取连接封装成一个工具类
- 简单JDBC连接池的实现
- JDBC实现简单的连接池代码
- JDBC连接池的简单实现
- JDBC连接池的简单实现
- JDBC以及相关技术学习(一)----第一个JDBC程序
- JDBC以及相关技术学习(八)----JDBC元数据
- JNDI与JDBC比较以及连接池的技术
- JNDI与JDBC比较以及连接池的技术 .
- JNDI与JDBC比较以及连接池的技术
- JNDI与JDBC比较以及连接池的技术
- JNDI与JDBC比较以及连接池的技术
- JDBC以及相关技术学习(五)----PreparedStatement特殊参数处理
- JDBC以及相关技术学习(六)----批量SQL处理
- JDBC以及相关技术学习(三)----运载查询结果的利器ResultSet
- JDBC以及相关技术学习(十)----拦截Connection的close方法
- JDBC(2):核心类、接口以及实现简单连接
- Corona SDK等跨平台开发工具
- fflush(stdout)的使用
- OnDeviceChange(ON_WM_DEVICECHANGE)
- SQL Server索引进阶第一篇:索引介绍
- 巧妙利用中国剩余定理(九度 1142)
- JDBC以及相关技术学习(九)----简单的连接池实现
- jquery自定义属性
- 从helloworld回顾程序的编译过程之三——静态链接
- Visio画UML用例图只需八步轻松实现
- c++强制类型转换:dynamic_cast、const_cast 、static_cast、reinterpret_cast
- Android SDK 21.1 发布,Android 开发工具包
- startup就ORA-03113:
- Best Time to Buy and Sell Stock II
- 如何创建一个滑出式导航面板(2)