为什么要使用连接池,这些基本也不用说那么多
以下为快速入门案例
包目录结构
配置文件c3p0-config.xml
<c3p0-config> <!-- 默认配置,如果没有指定自己的,则使用这个配置 --> <default-config> <property name="checkoutTimeout">30000</property> <property name="idleConnectionTestPeriod">30</property> <property name="initialPoolSize">10</property> <property name="maxIdleTime">30</property> <property name="maxPoolSize">100</property> <property name="minPoolSize">10</property> <property name="maxStatements">200</property> <user-overrides user="test-user"> <property name="maxPoolSize">10</property> <property name="minPoolSize">1</property> <property name="maxStatements">0</property> </user-overrides> </default-config> <!-- 命名的配置 --> <named-config name="mytest"> <property name="driverClass">com.mysql.jdbc.Driver</property> <property name="jdbcUrl">jdbc:mysql://localhost:3306/kafka2hive?useUnicode=true&characterEncoding=UTF-8</property> <property name="user">root</property> <property name="password">123456</property> <!-- 如果池中数据连接不够时一次增长多少个 --> <property name="acquireIncrement">5</property> <property name="initialPoolSize">20</property> <property name="minPoolSize">10</property> <property name="maxPoolSize">40</property> <property name="maxStatements">0</property> <property name="maxStatementsPerConnection">5</property> </named-config> </c3p0-config>
JdbcC3p0Util
public class JdbcC3p0Util { private static ComboPooledDataSource dataSource; static{ try { dataSource = new ComboPooledDataSource(); dataSource.setDriverClass("com.mysql.jdbc.Driver"); dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/kafka2hive"); dataSource.setUser("root"); dataSource.setPassword("123456"); // * 最大连接数 dataSource.setMaxPoolSize(50); // * 最小连接数 dataSource.setMinPoolSize(10); // * 每次增长的个数 dataSource.setAcquireIncrement(5); } catch (PropertyVetoException e) { e.printStackTrace(); } } public static Connection getConnection() throws SQLException{ return dataSource.getConnection(); } public static void main(String[] args) throws Exception { System.out.println(getConnection()); } }
JdbcC3p0Util2
public class JdbcC3p0Util2 { private static ComboPooledDataSource dataSource; static{ dataSource = new ComboPooledDataSource("mytest"); //c3p0-config.xml <named-config name="mytest"> 配置名称 } public static Connection getConnection() throws SQLException{ return dataSource.getConnection(); } public static void main(String[] args) throws Exception { System.out.println(getConnection()); } }
根据自己业务场景使用,推荐使用第二种!!