public class ApacheDBUtils {
@Test
public void testQueryMany() throws SQLException {
// 得到连接 druid
Connection connect = DruidUtil.connect();
QueryRunner queryRunner = new QueryRunner();
String sql = "select * from actor where id >= ?";
/**
* query 方法:执行sql语句 ---> 得到resultSet ---> 封装到 arrayList中
* new BeanListHandler<>(Actor.class) -- 在将 resultSet封装到arrayList中
* 底层使用反射机制,去获取Actor的属性,完成封装
* 1 就是给 sql语句中的? 赋值,可以写多个
* resultSet, preparedStatement在底层中产生并关闭
*/
/**
* query 方法源码:
* if (conn == null) { // 先进行判断,如果没有连接,就抛出异常
* throw new SQLException("Null connection");
* } else if (sql == null) { // 如果没有sql语句,但有连接,就关闭连接后抛出异常“Null SQL statement”
* if (closeConn) {
* this.close(conn);
* }
*
* throw new SQLException("Null SQL statement");
* } else if (rsh == null) { // 如果没有封装的类型,但有连接,同样关闭连接后抛出异常
* if (closeConn) {
* this.close(conn);
* }
*
* throw new SQLException("Null ResultSetHandler");
* } else {
* PreparedStatement stmt = null; 这里初始化一些工具
* ResultSet rs = null;
* Object result = null;
*
* try {
* stmt = this.prepareStatement(conn, sql); 创建prepareStatement
* this.fillStatement(stmt, params); 将形参赋值给 ?
* rs = this.wrap(stmt.executeQuery()); 用prepareStatement执行sql语句,executeQuery()该方法返回一个结果集
* result = rsh.handle(rs); 将结果集封装在一个ArrayList中,这里底层会用到反射机制对传入的Class类型进行解析
* } catch (SQLException var33) {
* this.rethrow(var33, sql, params);
* } finally {
* try {
* this.close(rs);
* } finally {
* this.close(stmt);
* if (closeConn) {
* this.close(conn);
* }
*
* }
* }
*
* return result;
*/
List<Actor> list =
queryRunner.query(connect, sql, new BeanListHandler<>(Actor.class), 1);
// Actor actor = new Actor();
// 上述声明后再使用到增强for循环是错误的,查询得,需要定义新的局部变量
for(Actor actor : list){
System.out.println(actor);
}
connect.close();
}
}
Apache dbUtils工具类的初使用和query方法的源码浅析
最新推荐文章于 2024-04-11 09:52:25 发布
本文介绍了如何使用Apache dbUtils进行数据库操作,特别是深入解析了`query`方法的源码,展示了如何执行SQL查询并利用BeanListHandler将结果集转换为Actor对象列表。通过一个具体的测试案例,演示了从数据库查询actor数据并打印的过程。
3061

被折叠的 条评论
为什么被折叠?



