连接池
一、C3p0连接
c3p0被称为数据库链接池,用来管理数据库链接的获取和存储。
ComboPooledDataSource存储数据源接口池。通过ComboPooledDataSource获取dateSource即数据源,可从中获取数据库的链接。
1.C3p0连接
第一种
ComboPooledDataSource cpds = new ComboPooledDataSource();
cpds.setDriverClass( "com.mysql.jdbc.Driver" ); //loads the jdbc driver
cpds.setJdbcUrl( "jdbc:mysql://localhost:3306/jdbc?useSSL=false" );
cpds.setUser("root");
cpds.setPassword("root");
Connection connection = cpds.getConnection();
第二种
ComboPooledDataSource dataSource = new ComboPooledDataSource(); //文件默认调用
Connection connection = dataSource.getConnection();
C3p0数据库连接池,默认先加载xml文件,如果没有找到xml文件,就会加载properties文件。
C3p0的配置文件xml文件
<c3p0-config>
<default-config>
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql://localhost:3306/jdbc</property>
<property name="user">root</property>
<property name="password">root</property>
<!-- 程序启动时候 默认在连接池里创建的连接数 -->
<property name="initialPoolSize">10</property>
<property name="maxIdleTime">30</property>
<property name="maxPoolSize">100</property>
<property name="minPoolSize">10</property>
</default-config>
<named-config name="dev">
<property> name="jdbcUrl">jdbc:mysql://localhost:3306/jdbc?useSSL=false</property>
</named-config>
</c3p0-config>
c3p0.properties 文件
c3p0.driverClass=com.mysql.jdbc.Driver
c3p0.jdbcUrl=jdbc:mysql://localhost:3306/jdbc
c3p0.user=root
c3p0.password=root
二、Druid连接池
DRUID是阿里巴巴开源平台上一个数据库连接池实现,它结合了C3P0、DBCP、PROXOOL等DB池的优点,同时加入了日志监控,可以很好的监控DB池连接和SQL的执行情况,可以说是针对监控而生的DB连接池(据说是目前最好的连接池,不知道速度有没有BoneCP快)。
第一种
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/jdbc");
dataSource.setUsername("root");
dataSource.setPassword("root");
DruidDataSourceC3P0Adapter druidDataSourceC3P0Adapter = new DruidDataSourceC3P0Adapter();
java.sql.Connection connection= druidDataSourceC3P0Adapter.getConnection();
第二种
Properties properties = new Properties();
properties.load(DruidDemo2.class.getClassLoader().getResourceAsStream("alibaba.properties"));
//面向接口编程
DruidDataSource dataSource = (DruidDataSource) DruidDataSourceFactory.createDataSource(properties);
/*int initialSize = dataSource.getInitialSize();
System.out.println("初始化连接池的大小"+initialSize);*/
Connection connection = dataSource.getConnection();
alibaba.properties文件
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/jdbc?useSSL=false
username=root
password=root
filters=stat
initialSize=2
maxActive=300
maxWait=60000
timeBetweenEvictionRunsMillis=60000
minEvictableIdleTimeMillis=300000
validationQuery=SELECT 1
testWhileIdle=true
testOnBorrow=false
testOnReturn=false
poolPreparedStatements=false
maxPoolPreparedStatementPerConnectionSize=200