建立C3P0資料來源,

來源:互聯網
上載者:User

建立C3P0資料來源,

[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();}}}}

引用時直接調用靜態方法即可。


著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

相關關鍵詞:
相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.