java c3po_java—c3p0utils封装

本文介绍了如何使用Java封装C3P0连接池工具类C3P0Utils,以减少代码量并简化数据库连接获取过程。通过创建静态内部类 ComboPooledDataSource 并提供静态方法获取DataSource和Connection,使得在测试类中可以方便地调用getConnection()进行数据库操作。在测试类Test_c3p0util中展示了使用C3P0Utils进行插入操作的步骤,包括获取连接、编写SQL、设置参数、执行SQL和释放资源。
摘要由CSDN通过智能技术生成

封装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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值