完成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(); } } } }
测试类:
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); } }
测试结果:
学习的博客多用于在笔记中,防止笔记过于臃肿,所以将样例及运行结果放在博客中,后以超链接的形式记录在笔记中,所以有些博文过于单薄。如果有小伙伴遇到问题欢迎评论,看到就会回复,学渣一枚,加油努力。