JAVA接続プール技術(javaデータベースプログラミング)
1747 ワード
, , , 。
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;
}
}