【Java】WEB应用 DBUtils实用工具包

DBUtils可以帮助开发者完成数据的封装(结果集到Java对象的映射)
ResultHandler 接口是用来处理结果集,可以将查询到的结果集转换成Java对象,提供了四种实现类
1、BeanHandler 将结果集映射成Java对象
2、BeanLlistHandler 将结果集映射成List集合,List
3、MapHandler 将结果集映射成Map对象
4、MapListHandler 将结果集映射成MapList集合
BeanHandler代码实例

    public static Student findByDBUtils(Integer id,String name) throws SQLException {
Student student = null;
Connection connection = null;
try
{
connection = MySQLUtil.getCon();
String sql= "select * from student where student_id = ? or sname = ?";
QueryRunner queryRunner = new QueryRunner();
student = queryRunner.query(connection,sql,new BeanHandler<>(Student.class),id,name); //封装结果集
}
catch (Exception e)
{
e.printStackTrace();
}
finally {
connection.close();
}
return student;
}
}

Student类
private Integer student_id;
private String sno;
private String ssex;
private String sname;
private String sid;
private Date sbirthday;
private String sphone;
private String sclass;

Student类里面的属性生成set和get方法,属性名跟数据库字段名一直,即可获取数据
BeanListHandler
public static void findByDBUtils()
{
List<Student> student = null;
Connection connection = null;
try
{
connection = MySQLUtil.getCon();
String sql= "select * from student";
QueryRunner queryRunner = new QueryRunner();
student = queryRunner.query(connection,sql,new BeanListHandler<>(Student.class)); //封装结果集
System.out.println(student);
}
catch (Exception e)
{
e.printStackTrace();
}
finally {
try {
connection.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}

MapHandler
public static void findByDBUtils()
{
Student student = null;
Connection connection = null;
try
{
connection = MySQLUtil.getCon();
String sql= "select * from student";
QueryRunner queryRunner = new QueryRunner();
Map map = queryRunner.query(connection,sql,new MapHandler()); //封装结果集
System.out.println(map);
}
catch (Exception e)
{
e.printStackTrace();
}
finally {
try {
connection.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}

MapListHandler
public static void findByDBUtils()
{
Student student = null;
Connection connection = null;
try
{
connection = MySQLUtil.getCon();
String sql= "select * from student";
QueryRunner queryRunner = new QueryRunner();
List<Map<String,Object>> map = queryRunner.query(connection,sql,new MapListHandler()); //封装结果集
JSONArray jsonObject = new JSONArray(Arrays.asList(map.toArray())); //Map转JSON
System.out.println(jsonObject);
}
catch (Exception e)
{
e.printStackTrace();
}
finally {
try {
connection.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}

blank