將c3p0封裝為一個(gè)JDBCUtils類茬斧。管理數(shù)據(jù)庫的連接和使用。
public class JDBCTools {
//處理數(shù)據(jù)庫事務(wù)的
//提交事務(wù)
public static void commit(Connection connection){
if(connection != null){
try {
connection.commit();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
//回滾事務(wù)
public static void rollback(Connection connection){
if(connection != null){
try {
connection.rollback();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
//開始事務(wù)
public static void beginTx(Connection connection){
if(connection != null){
try {
connection.setAutoCommit(false);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
private static DataSource dataSource = null;
//數(shù)據(jù)庫連接池應(yīng)只被初始化一次.
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 {
//數(shù)據(jù)庫連接池的 Connection 對(duì)象進(jìn)行 close 時(shí)
//并不是真的進(jìn)行關(guān)閉, 而是把該數(shù)據(jù)庫連接會(huì)歸還到數(shù)據(jù)庫連接池中.
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
c3p0-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
<named-config name="helloc3p0">
<!-- 指定連接數(shù)據(jù)源的基本屬性 -->
<property name="user">root</property>
<property name="password">1230</property>
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql:///atguigu</property>
<!-- 若數(shù)據(jù)庫中連接數(shù)不足時(shí), 一次向數(shù)據(jù)庫服務(wù)器申請(qǐng)多少個(gè)連接 -->
<property name="acquireIncrement">5</property>
<!-- 初始化數(shù)據(jù)庫連接池時(shí)連接的數(shù)量 -->
<property name="initialPoolSize">5</property>
<!-- 數(shù)據(jù)庫連接池中的最小的數(shù)據(jù)庫連接數(shù) -->
<property name="minPoolSize">5</property>
<!-- 數(shù)據(jù)庫連接池中的最大的數(shù)據(jù)庫連接數(shù) -->
<property name="maxPoolSize">10</property>
<!-- C3P0 數(shù)據(jù)庫連接池可以維護(hù)的 Statement 的個(gè)數(shù) -->
<property name="maxStatements">20</property>
<!-- 每個(gè)連接同時(shí)可以使用的 Statement 對(duì)象的個(gè)數(shù) -->
<property name="maxStatementsPerConnection">5</property>
</named-config>
</c3p0-config>