YuFeng

JDBC C3P0 连接池配置
工具包下载:cp30.zipc3p0 是免费的开源连接池,在使用cp30前需要导入jar包,还需要手动添加配置文件...
扫描右侧二维码阅读全文
11
2018/11

JDBC C3P0 连接池配置

工具包下载:
cp30.zip

c3p0 是免费的开源连接池,在使用cp30前需要导入jar包,还需要手动添加配置文件.并且指定文件名和格式c3p0-config.xml

//先定义C3P0工具类
public class C3p0utils {
    
    private static ComboPooledDataSource cpds = new ComboPooledDataSource();
    
    public static Connection getConnection() {
        try {
            return cpds.getConnection();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
    
    public static DataSource getDataSource() {
        return cpds;
    }
    
    public static void replace(Connection conn,Statement stat, ResultSet set) {
        if(set != null) {
            try {
                set.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        
        if(stat != null) {
            try {
                set.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        
        if(conn != null) {
            try {
                set.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

//定义C3P0.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/mytest</property>
        <property name="user">root</property>
        <property name="password">password</property>
        <property name="initialPoolSize">5</property>
        <property name="maxPoolSize">20</property>
    </default-config>

    <named-config name="配置名">
        <property name="driverClass">com.mysql.jdbc.Driver</property>
        <property name="jdbcUrl">jdbc:mysql:///web08</property>
        <property name="user">root</property>
        <property name="password">root</property>
    </named-config>


</c3p0-config>
            
            
//使用C3P0进行数据库连接
            public class C3p0Connection {
    public static void main(String[] args) {
        Connection connection = null;
        PreparedStatement stmt = null;
        ResultSet set = null;
        try {
            connection = C3p0utils.getConnection();
            String sql = "select * from user";
            stmt = connection.prepareStatement(sql);
            //stmt.setInt(1, 1);
            set = stmt.executeQuery();
            while(set.next()) {
                System.out.println(set.getInt("uid"));
                System.out.println(set.getString("name"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            C3p0utils.replace(connection, stmt, set);
        }
    }
}
Last modification:June 11th, 2019 at 12:25 pm
If you think my article is useful to you, please feel free to appreciate

Leave a Comment