publicclassApDBUtils_use{publicvoidtestQueryMany()throwsSQLException{// 返回结果是多行的情况Connection connection =JDBCUtilsByDruid.getConnection();// 创建QueryRunner对象QueryRunner queryRunner =newQueryRunner();String sql ="select * from actor where id >= ?";// 1.connection -> 链接// 2.sql -> sql语句// 3.new BeanListHandler<>(Actor.class) -> 传入Actor.class,通过反射机制得到Actor的属性->封装到ArrayList// 4.参数1 -> 替代占位符?,可以传入多个参数List<Actor> list = queryRunner.query(connection, sql,newBeanListHandler<>(Actor.class),1);for(Actor a: list){System.out.println("\n"+ a);}// query获取到ArrayList之后自动关闭ResultSet和preparedStatement,所以只需要关闭connection
connection.close();}publicvoidtestQuerySingle()throwsException{Connection connection =JDBCUtilsByDruid.getConnection();// 创建QueryRunner对象QueryRunner queryRunner =newQueryRunner();String sql ="select * from actor where id = ?";// 返回单行记录<-->单个对象new BeanHandler<>(Actor.class)Actor actor = queryRunner.query(connection, sql,newBeanHandler<>(Actor.class),4);System.out.println(actor);
connection.close();}publicvoidtestQueryObject()throwsException{// 返回单行单列,也就是返回一个objectConnection connection =JDBCUtilsByDruid.getConnection();// 创建QueryRunner对象QueryRunner queryRunner =newQueryRunner();String sql ="select name from actor where id = ?";// new ScalarHandler()返回一个对象Object o = queryRunner.query(connection, sql,newScalarHandler(),4);System.out.println(o);
connection.close();}}
DML
publicvoidtestDML()throwsException{Connection connection =JDBCUtilsByDruid.getConnection();// 创建QueryRunner对象QueryRunner queryRunner =newQueryRunner();String sql ="update actor set name = ? where id = ?";// queryRunner.update可以执行dml操作// 返回值是受影响的行数
queryRunner.update(connection,sql,"cyt",1);
connection.close();}