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);
}


 }




原创粉丝点击