數據庫複用代碼【c3p0配置文件、數據庫鏈接池】

前言

爲了複用,記載一些之前寫過的工具類、方法java

c3p0配置文件【c3p0-config.xml】

<?xml version="1.0" encoding="UTF-8" ?>
<c3p0-config>
    <default-config>
        <property name="driverClass">com.mysql.jdbc.Driver</property>
        <property name="jdbcUrl">jdbc:mysql://localhost:3306/zhongfucheng?characterEncoding=utf8</property>
        <property name="user">root</property>
        <property name="password">root</property>

        <property name="acquireIncrement">5</property>
        <property name="initialPoolSize">10</property>
        <property name="minPoolSize">5</property>
        <property name="maxPoolSize">20</property>
    </default-config>

    <named-config name="mysql">
        <property name="driverClass">com.mysql.jdbc.Driver</property>
        <property name="jdbcUrl">jdbc:mysql://localhost:3306/zhongfucheng</property>
        <property name="user">root</property>
        <property name="password">root</property>

        <property name="acquireIncrement">5</property>
        <property name="initialPoolSize">10</property>
        <property name="minPoolSize">5</property>
        <property name="maxPoolSize">20</property>
    </named-config>


    <named-config name="oracle">
        <property name="driverClass">oracle.jdbc.driver.OracleDriver</property>
        <property name="jdbcUrl">jdbc:oracle:thin:@//localhost:1521/事例名...</property>
        <property name="user">用戶名</property>
        <property name="password">密碼</property>

        <property name="acquireIncrement">5</property>
        <property name="initialPoolSize">10</property>
        <property name="minPoolSize">5</property>
        <property name="maxPoolSize">20</property>
    </named-config>
</c3p0-config>

數據庫鏈接池c3p0

import com.mchange.v2.c3p0.ComboPooledDataSource;

    import javax.sql.DataSource;
    import java.sql.Connection;
    import java.sql.SQLException;

    /** * Created by ozc on 2017/2/22. */
    public class Utils2DB {

        private static ComboPooledDataSource comboPooledDataSource = null;

            static {

                //它會自動尋找配置文件,節點爲mysql的數據庫
                comboPooledDataSource = new ComboPooledDataSource();
            }


        public static DataSource getDataSource() {
            return comboPooledDataSource ;
        }

        public static Connection connection() {
            try {
                return comboPooledDataSource.getConnection();
            } catch (SQLException e) {
                e.printStackTrace();
                throw new RuntimeException("數據庫初始化失敗了!");
            }
        }
    }
相關文章
相關標籤/搜索