数据库连接池(没加线程同步)

Java连接池实现
本文介绍了一个简单的Java数据库连接池实现,通过Connpool类管理多个数据库连接,支持连接的获取和释放,有效提高数据库访问效率。

 

package conn;

import java.sql.*;
import java.util.* ;
public class Connpool {
	List<Connection> live=new ArrayList<Connection>() ;
	List<Connection> detail=new ArrayList<Connection>() ;
	public List<Connection> addConn(int i){
		for(int t=0;t<i;t++){
		   live.add(this.getConn()) ;
		}
		return live ;
	}
	public Connection getConn(){
		Connection conne=null ;
		try{
		Class.forName("com.mysql.jdbc.Driver");
		conne=DriverManager.getConnection("jdbc:mysql://localhost:3306/lring","root","root") ;
		}catch(Exception e){
			e.printStackTrace() ;
		}
		return conne ;
	}
	public void close(Connection conn){
		this.live.add(conn) ;
		this.detail.remove(conn) ;
	}
	 public Connection  ceshi(){
		Connection ccvt1=this.live.get(0) ;
		this.detail.add(ccvt1) ;
		this.live.remove(ccvt1) ;
		this.close(ccvt1) ;
		return ccvt1 ;
	}
	 static public void main(String[] args){
		 Connpool pool=new Connpool() ;
		 long s1=System.nanoTime() ;
		  pool.addConn(5) ;
		 long s2=System.nanoTime() ;
		 System.out.println(s2-s1) ;
		 for(int a=0;a<100;a++){
			 Connection cnn= pool.ceshi() ;
			System.out.println(cnn.hashCode()) ;
			 System.out.println("执行次数为"+a) ;
		 }
	 }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值