日期:2014-05-16 浏览次数:20441 次
需要的jar包:1.commons-dbcp.jar
????????????????? ?2.commons-collections.jar
?????????????????? 3.commons-pool.jar
import java.io.FileInputStream; import java.io.IOException; import java.sql.Connection; import java.sql.SQLException; import java.util.Properties; import javax.sql.DataSource; import org.apache.commons.dbcp.BasicDataSource; public class DbcpConnection { private static DataSource dataSource; private static Connection con; public DbcpConnection(){ } public static Connection getConnection() { if (dataSource == null) { initDataSource(); } try { con = dataSource.getConnection(); print(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return con; } @SuppressWarnings("deprecation") public static void initDataSource() { FileInputStream is=null; Properties p = new Properties(); String driverClassName=null; String url=null; String username=null; String password=null; int initialSize=0; int minIdle=0; int maxIdle=0; int maxWait=0; int maxActive=0; try { is= new FileInputStream("dbcp.properties"); p.load(is); driverClassName = p.getProperty("dbcp.driverClassName"); url = p.getProperty("dbcp.url"); username = p.getProperty("dbcp.username"); password = p.getProperty("dbcp.password"); initialSize = Integer.parseInt(p.getProperty("dbcp.initialSize")); minIdle = Integer.parseInt(p.getProperty("dbcp.minIdle")); maxIdle = Integer.parseInt(p.getProperty("dbcp.maxIdle")); maxWait = Integer.parseInt(p.getProperty("dbcp.maxWait")); maxActive = Integer.parseInt(p.getProperty("dbcp.maxActive")); } catch (NumberFormatException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ try { is.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } BasicDataSource ds = new BasicDataSource(); ds.setUrl(url); ds.setDriverClassName(driverClassName); ds.setUsername(username); ds.setPassword(password); ds.setInitialSize(initialSize); // 初始的连接数; ds.setMaxActive(maxActive); ds.setMinIdle(minIdle); ds.setMaxIdle(maxIdle); ds.setMaxWait(maxWait); //ds.setRemoveAbandoned(true); //ds.setRemoveAbandonedTimeout(2000); dataSource = ds; } /* 用于测试连接状态的方法*/ public static void print(){ BasicDataSource ds=(BasicDataSource)dataSource; System.out.println(ds.getInitialSize()); System.out.println(ds.getNumActive()); System.out.println(ds.getNumIdle()); System.out.println(ds.getDefaultAutoCommit()); } }
?
2.数据库的连接属性的配置文件:dbcp.properties
dbcp.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver dbcp.url=jdbc:sqlserver://localhost:1433;DatabaseName=Library;userName=sa;password=123456 dbcp.username=sa dbcp.password=123456 dbcp.initialSize=10 dbcp.minIdle=5 dbcp.maxIdle=15 dbcp.maxWait=3000 dbcp.maxActive=20
?