其他分享
首页 > 其他分享> > dbutils介绍

dbutils介绍

作者:互联网

DBUtils介绍

如果只使用JDBC进行开发,会发现冗余代码过多,为了简化JDBC开发,采用apache commons组件一个成员:DBUtils。 
DBUtils是java编程中的数据库操作实用工具,小巧简单实用。 
DBUtils封装了对JDBC的操作,简化了JDBC操作,可以少写代码。 
Dbutils三个核心功能介绍: 
1. QueryRunner中提供对sql语句操作的API. 
2. ResultSetHandler接口,用于定义select操作后,怎样封装结果集. 
3. DbUtils类,它就是一个工具类,定义了关闭资源与事务处理的方法

2 QueryRunner 类

2.1 QueryRunner核心类

2.2 实现 insert

这里写图片描述

import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;

/**
 * 编写JDBC工具类,获取数据库连接
 * 读取配置文件,获取连接,执行一次,
 */
public class JDBCUtilsConfig {
    private static Connection con;
    private static String driverClass;
    private static String url;
    private static String username;
    private static String password;

    static {
        try {
            readConfig();
            Class.forName(driverClass);
            con = DriverManager.getConnection(url, username, password);
        }catch(Exception ex){
            throw new RuntimeException("数据库连接失败");
        }

    }

    public static void readConfig()throws Exception{
        InputStream in = JDBCUtilsConfig.class.getClassLoader().getResourceAsStream("database.properties");
        Properties pro = new Properties();
        pro.load(in);
        driverClass = pro.getProperty("driverClass");
        url = pro.getProperty("url");
        username = pro.getProperty("username");
        password = pro.getProperty("password");
    }

    public static Connection getConnection() {
        return con;
    }

}
import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * 使用QueryRunner 类,实现对数据表操作
 * insert delete update
 */
public class QueryRunnerDemo {
    private static Connection con=JDBCUtilsConfig.getConnection();

    public static void main(String[] args)throws SQLException {
        insert();
    }

    public static void insert() throws SQLException {
        QueryRunner qr = new QueryRunner();
        String sql = "INSERT INTO sort (sname,sprice,sdesc) VALUES (?,?,?)";
        Object[] params = {"体育用品", 289.32, "购买体育用品"};
        int row = qr.update(con, sql, params);
        System.out.println(row);
        DbUtils.closeQuietly(con);
    }

}

2.3 update操作

  public static void update() throws SQLException {
        QueryRunner qr = new QueryRunner();
        String sql = "UPDATE sort SET sname=?,sprice=?,sdesc=? WHERE sid=?";
        Object[] params = {"花卉", 100.89, "情人节玫瑰", 4};
        int row = qr.update(con, sql, params);
        System.out.println(row);
        DbUtils.closeQuietly(con);
    }

2.4 delete 操作

   public static void delete() throws SQLException {
        QueryRunner qr = new QueryRunner();
        String sql = "DELETE FROM sort WHERE sid=?";
        int row = qr.update(con, sql, 8);
        System.out.println(row);
        /*
        * 判断 insert,update,delete 执行是否成功
        * 对返回值row判断,大于0,执行成功
        * */
        DbUtils.closeQuietly(con);
    }

3 QueryRunner 查询操作

3.1 ResultSetHandler 结果集处理类

3.2 JavaBean

JavaBean就是一个类,在开发中常用封装数据。具有如下特性 
- 需要实现接口:java.io.Serializable ,通常实现接口这步骤省略了,不会影响程序。 
- 提供私有字段:private 类型 字段名; 
- 提供getter/setter方法: 
- 提供无参构造

3.3 query方法

query(Connection conn, String sql, ResultSetHandler<T> rsh, Object... params) ,用来完成表数据的查询操作 
- ResultSetHandler 结果集的处理方式,传递ResultSetHandler接口实现类; 
- 注意:query返回值是泛型,返回的是泛型,具体返回值随结果集处理方式变化;

3.3.1 ArrayHandler,将结果集的第一行存储到对象数组 Object[]

public static void arrayHandler() throws SQLException {
        QueryRunner qr = new QueryRunner();
        String sql = "SELECT * FROM sort";
        Object[] result = qr.query(con, sql, new ArrayHandler());
        for(Object obj:result){
            System.out.println(obj);
        }
    }

3.3.2 ArrayListHandler

public static void arrayListHandler() throws SQLException {
        QueryRunner qr = new QueryRunner();
        String sql = "SELECT * FROM sort";
        List<Object[]> result = qr.query(con, sql, new ArrayListHandler());
        for(Object[] objs: result){
            for(Object obj:objs){
                System.out.print(obj+" ");
            }
            System.out.println();
        }
    }

3.3.3 BeanHandler

public class Sort {
    private int sid;
    private String sname;
    private double sprice;
    private String sdesc;

    public Sort() {
    }

    public Sort(int sid, String sname, double sprice, String sdesc) {
        this.sid = sid;
        this.sname = sname;
        this.sprice = sprice;
        this.sdesc = sdesc;
    }

    @Override
    public String toString() {
        return "Sort{" + "sid=" + sid + ", sname='" + sname + '\'' + ", sprice=" + sprice + ", sdesc='" + sdesc + '\'' + '}';
    }

    public int getSid() {
        return sid;
    }

    public void setSid(int sid) {
        this.sid = sid;
    }

    public String getSname() {
        return sname;
    }

    public void setSname(String sname) {
        this.sname = sname;
    }

    public double getSprice() {
        return sprice;
    }

    public void setSprice(double sprice) {
        this.sprice = sprice;
    }

    public String getSdesc() {
        return sdesc;
    }

    public void setSdesc(String sdesc) {
        this.sdesc = sdesc;
    }
}
//注意:被封装成数据到JavaBean对象,Sort类必须有空参数构造
    public static void beanHandler() throws SQLException {
        QueryRunner qr = new QueryRunner();
        String sql = "SELECT * FROM sort";
        Sort s = qr.query(con, sql, new BeanHandler<Sort>(Sort.class));
        System.out.println(s);
    }

3.3.4 BeanListHanlder

 /*
    * BeanListHandler 将数据结果集的每一行封装成JavaBean对象
    * 多个JavaBean对象封装到List集合
    * */
    public static void beanListHandler()throws SQLException {
        QueryRunner qr = new QueryRunner();
        String sql = "SELECT * FROM sort";
        List<Sort> list = qr.query(con, sql, new BeanListHandler<Sort>(Sort.class));
        for(Sort s:list){
            System.out.println(s);
        }
    }

3.3.5 ColumnListHandler

/*
    * 结果集指定列的数据,存储到List集合,
    * List<Object> 每个列数据类型不同
    * */
    public static void columnListHandler() throws SQLException {
        QueryRunner qr = new QueryRunner();
        String sql = "SELECT * FROM sort";
        List<Object> list = qr.query(con, sql, new ColumnListHandler<Object>("sname"));
        for(Object obj:list){
            System.out.println(obj);
        }
    }

这里写图片描述

3.3.6 ScalarHandler

  /*
    * ScalarHandler,对于查询后只有1个结果
    * */
    public static void scalarHandler()throws SQLException {
        QueryRunner qr = new QueryRunner();
        String sql = "SELECT COUNT(*) FROM sort";
        long count = qr.query(con, sql, new ScalarHandler<Long>());
        System.out.println(count);
    }

这里写图片描述

3.3.7 MapHandler

/*
    * ScalarHandler,对于查询后只有1个结果
    * */
    public static void scalarHandler() throws SQLException {
        QueryRunner qr = new QueryRunner();
        String sql = "SELECT COUNT(*) FROM sort";
        long count = qr.query(con, sql, new ScalarHandler<Long>());
        System.out.println(count);
    }

这里写图片描述

3.3.8 MapListHandler

/*
    * 将结果集每一行存储到Map集合,键:列名, 值:数据
    * Map集合过多,存储到List 集合
    * */
    public static void mapListHandler()throws SQLException {
        QueryRunner qr = new QueryRunner();
        String sql = "SELECT * FROM sort";
        List<Map<String, Object>> list = qr.query(con, sql, new MapListHandler());
        for(Map<String,Object> map: list){
            for(String key:map.keySet()){
                System.out.print(key+"--"+map.get(key));
            }
            System.out.println();
        }
    }

这里写图片描述

标签:qr,String,介绍,QueryRunner,sql,new,dbutils,public
来源: https://www.cnblogs.com/qiu18359243869/p/14311578.html