完成c3p0工具类读取配置文件方式并测试

C3P0工具类:

public class C3P0Util {
    //创建c3p0连接池对象

    private static ComboPooledDataSource cpds = new ComboPooledDataSource();
    private C3P0Util(){

    }

    //定义静态方法,获取Connection对象
    public static Connection getConnection() throws SQLException {
        return cpds.getConnection();
    }
    public static void release(Connection con, Statement stmt, ResultSet rs){
        if (con != null){
            try {
                con.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (rs != null){
            try {
                rs.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
}
View Code

测试类:

public class C3P0UtilDemo01 {
    public static void main(String[] args) throws SQLException {
        //1. 使用C3P0Util工具类获取连接Connection对象
        Connection con = C3P0Util.getConnection();

        //2. 定义sql语句,参数使用?代替
        String sql = "select * from users where uid = ?";

        //3. Connection对象获取执行sql语句的PreparedStatement对象,传递sql语句
        PreparedStatement pstmt = con.prepareStatement(sql);

        //4. PreparedStatement对象调用方法,给?赋值
        pstmt.setString(1,"u001");

        //5. PreparedStatement对象执行增删改查的方法,获取结果
        ResultSet rs = pstmt.executeQuery();
        //6. 处理结果
        if (rs.next()){
            Object uid = rs.getObject("uid");
            Object uname = rs.getObject("uname");
            Object upass = rs.getObject("upass");
            System.out.println("编号:"+uid+", 用户名:"+uname+", 密码:"+upass);
        }
        //7. 关闭资源
        C3P0Util.release(con,pstmt,rs);
    }
}
View Code

测试结果:

posted @ 2020-08-16 03:07  硬盘红了  阅读(199)  评论(0编辑  收藏  举报