编程语言
首页 > 编程语言> > java—c3p0utils封装

java—c3p0utils封装

作者:互联网

封装C3P0简化代码量

public class C3P0utils {
    private static ComboPooledDataSource dataSource = new ComboPooledDataSource();

    public static DataSource getDataSource(){
        return dataSource;
    }
    public static Connection getConnection(){
        try {
            return dataSource.getConnection();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}

测试类

public class Test_c3p0util {
    @Test
    public void test2() {
        Connection conn = null;
        PreparedStatement pstmt = null;

        try {
            // 1.获取连接
            conn = C3P0utils.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);
        }
    }
}

 

标签:封装,getConnection,c3p0utils,static,sql,java,public,conn,pstmt
来源: https://www.cnblogs.com/zhuzhiwei-2019/p/11300587.html