java—c3p0数据库连接池

配置文件  必须以c3p0-config.xml 命名

放置src目录中

<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>

    <default-config>
        <property name="driverClass">com.mysql.jdbc.Driver</property>
        <property name="jdbcUrl">jdbc:mysql:///db1</property>
        <property name="user">root</property>
        <property name="password"> </property>
        <property name="initialPoolSize">5</property>
        <property name="maxPoolSize">20</property>
    </default-config>

    <named-config name="itheima">
        <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 Test_c3p0 {

    @Test
    public void test2() {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ComboPooledDataSource dataSource = new ComboPooledDataSource();

        try {
            // 1.获取连接
            conn = dataSource.getConnection();
            // 2.编写sql语句
            String sql = "insert t1 (id,name) value (?,?)";
            // 3.获取执行sql语句对象
            pstmt = conn.prepareStatement(sql);
            // 4.设置参数
            pstmt.setInt(1, 7);
            pstmt.setString(2, "wuwuww");
            // 5.执行删除操作
            int row = pstmt.executeUpdate();
            if (row > 0) {
                System.out.println("删除成功!");
            } else {
                System.out.println("删除失败!");
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            // 6.释放资源
            JBDC_V2.release(conn, pstmt, null);
        }
    }
}

 

posted @ 2019-08-04 23:39  新手码农__威  阅读(737)  评论(0编辑  收藏  举报