日期:2014-05-16 浏览次数:20348 次
其实就是将数据库连接的Connection对象放在自定义的数据结构中,在需要数据库连接的时候,从该结构中取得即可。
?
package com.woo.demo.jdbc.util; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.LinkedList; public class MyDataSource { private String url="jdbc:hsqldb:hsql://localhost/woo"; private String user="sa"; private String pwd=""; private static LinkedList<Connection> connectionPool=new LinkedList<Connection>(); private final int connectionNum=5; private final int maxConnection=10; private int currentConnectionNum=0; public MyDataSource() { try { for (int i = 0; i < connectionNum; i++) { connectionPool.addLast(this.createConnection()); } } catch (Exception e) { throw new ExceptionInInitializerError(e); } } /** * 获取连接 * @return * @throws SQLException */ public Connection getConnection()throws SQLException{ synchronized (connectionPool) { if(connectionPool.size()>0){ currentConnectionNum++; return connectionPool.removeFirst(); } if(currentConnectionNum<maxConnection){ currentConnectionNum++; return this.createConnection(); } throw new SQLException("超过最大连接数"); } } /** * 释放连接 * @param con */ public void freeConnection(Connection con){ currentConnectionNum--; connectionPool.addLast(con); } /** * 创建连接 * @return */ private Connection createConnection(){ Connection con=null; try{ con=DriverManager.getConnection(url, user, pwd); } catch (Exception e) { throw new ExceptionInInitializerError(e); } return con; } }?