/**
* 用静态工厂方法管理一个唯一的可重用的连接
*/
public class ConnUtils {
private static Connection con;
//在静态代码块中创建与数据库的连接
static{
try{
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql:///test?characterEncoding=UTf8";
con = DriverManager.getConnection(url,"root","root");
}catch(Exception e){
throw new RuntimeException(e.getMessage(),e);
}
}
//使用一个静态方法-静态工厂方法,返回connection实例
public static Connection getCon(){
return con;
}
}
我感觉这种方式不怎么好因为每次只能获取一个连接所以
我推荐的方式是动态连数据库对close的方式进行增强操作
public class DBPool implements DataSource {
//声明一个池管理对象
private LinkedList<Connection> pool = new LinkedList<Connection>();
//在初始化这个DataSourc的子类时在构造方法设置多个连接
public DBPool(){
try{
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql:///test?characterEncoding=UTf8";
for(int i=0;i<3;i++){
final Connection con = DriverManager.getConnection(url,"root","root");
Object proxyedConn =
Proxy.newProxyInstance(DBPool.class.getClassLoader(),
new Class[]{Connection.class},
new InvocationHandler() {
public Object invoke(Object proxyedConnection, Method method, Object[] args)
throws Throwable {
if(method.getName().equals("close")){
synchronized (pool) {
pool.addLast((Connection) proxyedConnection);
pool.notify();
}
return null;
}
//目标方法的返回值
Object returnValue=method.invoke(con, args);
return returnValue;
}
});
pool.add((Connection) proxyedConn);
}
}catch(Exception e){
throw new RuntimeException(e.getMessage(),e);
}
}
public Connection getConnection() throws SQLException {
synchronized (pool) {
if(pool.size()==0){
try {
pool.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
return getConnection();
}
Connection con = pool.removeFirst();
System.err.println("siize:"+pool.size());
return con;
}
}
|
|