[Author]: kwu
创建C3P0数据源,实际开发中直接用JDBC连接数据库是非常少的。一般使用数据源的形式,C3P0是开源的数据源,实际项目用得非常多:
1、添加maven的支持
<dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> <version>0.9.1.2</version> </dependency>
2、配置C3P0,默认配置文件c3p0-config.xml:
<?xml version="1.0" encoding="UTF-8"?
> <c3p0-config> <named-config name="c3p0"> <property name="user">root</property> <property name="jdbcUrl">jdbc:mysql://localhost:3306/charts</property> <property name="driverClass">com.mysql.jdbc.Driver</property> <property name="password">root</property> <property name="acquireIncrement">5</property> <property name="initialPoolSize">5</property> <property name="minPoolSize">5</property> <property name="maxPoolSize">10</property> <property name="maxStatements">25</property> <property name="maxStatementsPerConnection">5</property> </named-config> </c3p0-config>
3、引用数据源
package com.hexun.utils; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import javax.sql.DataSource; import com.mchange.v2.c3p0.ComboPooledDataSource; /** * JDBC 的工具类 * * 当中包括: 获取数据库连接, 关闭数据库资源等方法. */ public class JDBCTools { //处理数据库事务的 //提交事务 public static void commit(Connection connection){ if(connection != null){ try { connection.commit(); } catch (SQLException e) { e.printStackTrace(); } } } //回滚事务 public static void rollback(Connection connection){ if(connection != null){ try { connection.rollback(); } catch (SQLException e) { e.printStackTrace(); } } } //開始事务 public static void beginTx(Connection connection){ if(connection != null){ try { connection.setAutoCommit(false); } catch (SQLException e) { e.printStackTrace(); } } } private static DataSource dataSource = null; //数据库连接池应仅仅被初始化一次. static{ dataSource = new ComboPooledDataSource("c3p0"); } public static Connection getConnection() throws Exception { return dataSource.getConnection(); } public static void releaseDB(ResultSet resultSet, Statement statement, Connection connection) { if (resultSet != null) { try { resultSet.close(); } catch (SQLException e) { e.printStackTrace(); } } if (statement != null) { try { statement.close(); } catch (SQLException e) { e.printStackTrace(); } } if (connection != null) { try { //数据库连接池的 Connection 对象进行 close 时 //并非真的进行关闭, 而是把该数据库连接会归还到数据库连接池中. connection.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
引用时直接调用静态方法就可以。