DBUtils 将结果集封装成对象

DBUtils

DBUtils可以帮助开发者完成数据的封装(结果集到java对象的映射)
通常情况下,得到ResultSet集数据后,需要进行遍历,如下图

ResultSet resultSet = statement.executeQuery(sql);
 while (resultSet.next()){
 Integer id = resultSet.getInt("id");
 String name = resultSet.getString(2);
 Double score = resultSet.getDouble(3);
 Date date = resultSet.getDate(4);
 System.out.println(id+"-"+name+"-"+score+"-"+date);
 }

但有个DBUtils工具可以封装对象

1、导入jar包

在这里插入图片描述
ResultHandler接口是用来处理结果集,可以将查询到的结果集转换成Java对象,提供了4种实现类。
1、BeanHandler 将结果集映射java对象
2、BeanListHandler将结果集映射成List集合
3、MapHandler将结果集映射成Map对象
4、MapListHandler将结果集映射成MapList

BeanHandler使用

package com.Chase.test;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import java.sql.*;
public class test {
    public static void main(String[] args) {
        Connection connection=null;
        Student student=null;
        try {
            ComboPooledDataSource dataSource= new ComboPooledDataSource("test");
            connection = dataSource.getConnection();
            System.out.println(connection);//打印出连接对象
            String sql="select * from student";
            QueryRunner queryRunner = new QueryRunner();
            student = queryRunner.query(connection,sql,new BeanHandler<>(Student.class));
            System.out.println(student);
        } catch (SQLException e)
        {
            e.printStackTrace();
        }finally {
            try {
                connection.close();//还回对象
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

MapListHandler的使用

package com.Chase.test;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.MapListHandler;

import java.sql.*;
import java.util.List;
import java.util.Map;

public class test {
    public static void main(String[] args) {
        Connection connection=null;
        Student student=null;
        try {
            ComboPooledDataSource dataSource= new ComboPooledDataSource("test");
            connection = dataSource.getConnection();
            System.out.println(connection);//打印出连接对象
            String sql="select * from student";
            QueryRunner queryRunner = new QueryRunner();
            List< Map<String,Object> > list = queryRunner.query(connection,sql,new MapListHandler());
            System.out.println(list);
        } catch (SQLException e)
        {
            e.printStackTrace();
        }finally {
            try {
                connection.close();//还回对象
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

本文素材来源于网上视频 + 手动操作,仅用于个人记录,如有侵权,请联系删除

你可能感兴趣的:(JAVAWeb,jdbc)