天天看點

C3P0 示例代碼C3P0 示例代碼

C3P0 示例代碼

這是一個連接配接SQL Server的C3P0的配置過程

代碼塊

import com.mchange.v2.c3p0.ComboPooledDataSource;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * Created by dan on 2015/12/2.
 */
public class C3P0JdbcUtil {
    private static ComboPooledDataSource ds = null;

    static {
        try{
            ds = new ComboPooledDataSource("SQLServer");
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public static Connection getConnection() throws SQLException{
        return ds.getConnection();
    }

    public static void release(Connection conn, Statement st, ResultSet rs){
        if (rs != null){
            try{
                rs.close();
            }catch(Exception e){
                e.printStackTrace();
            }
        }
        if (st != null){
            try{
                st.close();
            }catch(Exception e){
                e.printStackTrace();
            }
        }
        if (conn != null){
            try{
                conn.close();
            }catch(Exception e){
                e.printStackTrace();
            }
        }
    }
}
           

需要在配置檔案中指明連接配接的參數,檔案的名字必須是c3p0-config.xml:

<c3p0-config>

    <default-config>
        <property name="driverClass">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
        <property name="jdbcUrl">jdbc:sqlserver://127.0.0.1:1433</property>
        <property name="user">stu</property>
        <property name="password">123</property>

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

    <named-config name="SQLServer">
        <property name="driverClass">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
        <property name="jdbcUrl">jdbc:sqlserver://127.0.0.1:1433</property>
        <property name="user">stu</property>
        <property name="password">123</property>

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


</c3p0-config>
           

在xml中有一個預設的配置,有一個指定的配置,name屬性可被java程式用來綁定具體的資料庫配置:

new ComboPooledDataSource("SQLServer");
           

注意:使用上述java代碼的時候,c3p0-config.xml必須直接在src下方,而不是調用代碼的包中。