DBUtils 可以帮助开发者完成数据的封装(结果集到 Java 对象的映射)
使用前需要先导⼊ jar 包:commons-dbutils-1.7.jar
ResultHandler 接⼝是⽤来处理结果集,可以将查询到的结果集转换成 Java 对象,提供了 4 种实现类。被封装的目标类中必须有一个无参构造器
BeanHandler 将结果集映射成 Java 对象 Student
BeanListHandler 将结果集映射成 List 集合 List
MapHandler 将结果集映射成 Map 对象
MapListHandler 将结果集映射成 MapList 结合
public class DButilTest {
private static ComboPooledDataSource dataSource;
static{
dataSource =new ComboPooledDataSource("testc3p0");
}
public static void main(String[] args) {
Student student1=findById();
Student student2=findByDbutils();
System.out.println(student1);
System.out.println(student2);
int i = 0 ;
}
public static Student findByDbutils(){
Connection connection=null;
Student student =null;
try{
connection =dataSource.getConnection();
String sql="select * from student where id=4";
QueryRunner queryRunner =new QueryRunner();
System.out.println(queryRunner);
//根据student类的结构去封装结果集,student中必须有一个无参构造器
student = queryRunner.query(connection, sql, new BeanHandler<>(Student.class));
//将结果集映射成 List 集合 List
String sql2="select * from student ";
System.out.println(queryRunner.query(connection, sql2, new BeanListHandler<>(Student.class)));
String sql3="select * from student where id =?";
System.out.println(queryRunner.query(connection, sql3, new BeanListHandler<>(Student.class),13));
//将结果集映射成 Map 对象
String sql4="select * from student where id=4";
Map map =queryRunner.query(connection, sql4, new MapHandler());
System.out.println(map.get("name"));
//将结果集映射成 MapList 结合
String sql5="select * from student ";
List<Map<String,Object>> list= queryRunner.query(connection, sql5, new MapListHandler());
System.out.println(list);
}catch (SQLException e){
e.printStackTrace();
}finally {
try {
connection.close();
}catch (Exception e){
e.printStackTrace();
}
}
return student;
}
public static Student findById(){
Connection connection =null;
PreparedStatement preparedStatement =null;
ResultSet resultSet =null;
Student student =null;
try{
connection =dataSource.getConnection();
String sql="select * from student where id=4";
preparedStatement = connection.prepareStatement(sql);
resultSet =preparedStatement.executeQuery();
while(resultSet.next()){
Integer id=resultSet.getInt(1);
String name = resultSet.getString(2);
Double score = resultSet.getDouble(3);
Date birthday=resultSet.getDate(4);
student=new Student(id,name,score,birthday);
}
}catch (Exception e){
e.printStackTrace();
}finally {
try {
connection.close();
preparedStatement.close();
resultSet.close();
}catch (Exception e){
}
}
return student;
}
}