简单的数据库连接池练习

JDBC.conf配置文件:
driverClassname=com.mysql.jdbc.Driver
db_url=jdbc:mysql://localhost:3306/everdb
username=root
pwd=root
poolsize=10
连接池实现:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
import java.util.Vector;

public class ConnectionPool {

	private Vector<Connection> pool;
	
	private String url;
	
	private String username;
	
	private String password;
	
	private String driverClassName;
	
	private int poolSize = 2;
	
	private static ConnectionPool instance = null;

	private ConnectionPool()
	{
		init();
	}

	private void init() {
		pool = new Vector<Connection>(poolSize);
		readConfig();
		addConnection();
	}

	private void addConnection() {
		Connection conn = null;
		
		for (int i = 0; i <= poolSize; i++)
		{
			try {
				
				Class.forName(driverClassName);
				conn = DriverManager.getConnection(url, username, password);
				
				pool.add(conn);
				
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	private void readConfig() {
		try {

			Properties ps = new Properties();
			String Path = System.getProperty("user.dir") + "\\WebContent\\conf\\JDBC.conf";

			FileInputStream fs = new FileInputStream(Path);
			ps.load(fs);
			fs.close();
			
			this.url = ps.getProperty("db_url");
			this.username = ps.getProperty("username");
			this.password = ps.getProperty("pwd");
			this.driverClassName = ps.getProperty("driverClassname");
			this.poolSize = Integer.parseInt(ps.getProperty("poolsize"));
			
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.err.println("Get Config Data Error!");
		}
	}


	//获得实例,给外部类进行获取连接池
	public static ConnectionPool getInstance()
	{
		if (instance == null){
			instance = new ConnectionPool();
		}
		
		return instance;
	}
	
	public synchronized Connection getConnection()
	{
		if (pool.size() > 0 )
		{
			Connection conn = pool.get(0);
			pool.remove(conn);
			
			return conn;
		}else{
			
			return null;
		}
	}
	
	public synchronized void release(Connection conn)
	{
		pool.add(conn);
	}
	
	public synchronized void closePool(){
		for (int i=0; i<pool.size();i++){
			try {
				((Connection)pool.get(i)).close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			pool.remove(i);
		}
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值