JAVA连接池技术(java数据库编程)

连接池就是把对数据库的连接作为资源进行管理,把建立的连接放在内存中,要用的时候到连接池里取,使用完毕放回连接池即可。从而避免了建立连接消耗较大的资源
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.sql.*;


public class ConnectionPool {
	private List<Connection> pooList=null;//存放链接的集合
	Properties props=null;
	String userName=null;
	String password=null;
	String url=null;
	String driverName=null;
	int maxSize=0;
	Connection connection=null;
	private static ConnectionPool pool=null;//连接池对象
	private  ConnectionPool(int max)throws ClassNotFoundException,FileNotFoundException,IOException
	{
		userName="root";
		password="123456";
		url="jdbc:mysql://localhost/student";
		driverName="com.mysql.jdbc.Driver";
		maxSize=max;
		Class.forName(driverName);
		pooList=new ArrayList<Connection>();
		
		
	}
	//获得连接池
	public synchronized Connection getConnection()throws SQLException
	{
		
		if(pooList.size()==0)
		{
			for (int i = 0; i < maxSize; i++) 
			{
				connection=driverName.getConnection(url,userName,password);
				pooList.add(connection);
			}
		}
		return pooList.remove(0);
		
	}
	//关闭连接池
	public void close(Connection connection)throws SQLException
	{
		System.out.println(pooList.size());
		if(pooList.size()<maxSize)
		{
			pooList.add(connection);
			
		}
		else
		{
			connection.close();
		}
		System.out.println(pooList.size());
	}
	//获得一个连接池实例
	public static ConnectionPool getinstance()throws FileNotFoundException,ClassNotFoundException,IOException
	{
		if(pool==null)
		{
			pool=new ConnectionPool(10);
		}
		return pool;
	}
	
	

}

你可能感兴趣的:(JAVA连接池技术(java数据库编程))