zoukankan      html  css  js  c++  java
  • DBUtils

    什么是DBUtils及作用

    DBUtils是java编程中的数据库操作实用工具,小巧简单实用。

    DBUtils封装了对JDBC的操作,简化了JDBC操作。可以少写代码。

    1.对于数据表的读操作,他可以把结果转换成List,Array,Set等java集合,便于程序员操作;

    2.对于数据表的写操作,也变得很简单(只需写sql语句)

    3.可以使用数据源,使用JNDI,数据库连接池等技术来优化性能--重用已经构建好的数据库连接对象

    DBUtils的三个核心对象

    > QueryRunner类(提供了增删改查的方法)

    QueryRunner中提供对sql语句操作的API.

    它主要有三个方法

    query() 用于执行select

    update() 用于执行insert update delete

    batch() 批处理

    构造方法:

    > new QueryRunner(); 

    它的事务可以手动控制。

    也就是说此对象调用的方法(如:query、update、batrch)参数中要有Connection对象。

    > new QueryRunner(DataSource ds);

    它的事务是自动控制的。一个sql一个事务。

    此对象调用的方法(如:query、update、batrch)参数中无需Connection对象。

     

    方法:

    >ResultSetHandler接口(处理结果)

    用于定义select操作后,怎样封装结果集.

    ResultSetHandler下的所有结果处理器:

     

    //ArrayHandler:适合取1条记录。把该条记录的每列值封装到一个数组中Object[]

    //ArrayListHandler:适合取多条记录。把每条记录的每列值封装到一个数组中Object[],把数组封装到一个List中

    //ColumnListHandler:取某一列的数据。封装到List中。

    //KeyedHandler:取多条记录,每一条记录封装到一个Map中,再把这个Map封装到另外一个Map中,key为指定的字段值。

    //MapHandler:适合取1条记录。把当前记录的列名和列值放到一个Map中

    //MapListHandler:适合取多条记录。把每条记录封装到一个Map中,再把Map封装到List中

    //ScalarHandler:适合取单行单列数据

    BeanHandler

    BeanListHandler 

    > DBUtils类(关闭资源与事务的操作)

    它就是一个工具类,定义了关闭资源与事务处理的方法

    DBUtils快速入门

    > 导入jar包               

    > 创建QueryRunner对象

    > 使用query方法执行select语句

    > 使用ResultSetHandler封装结果集

    > 使用DbUtils类释放资源

    实现步骤:

    创建数据库及表:
    CREATE DATABASE day14;
    USE day14;
    
    create table account(
        id int primary key auto_increment,
        name varcar(50),
        money float
    );
    
    insert into account(name,money) values('aaa',1000);
    insert into account(name,money) values('bbb',1000);
    insert into account(name,money) values('ccc',1000);
    
    SELECT * FROM account;
    导入jar包:commons-dbutils-1.4.jar
    注意:c3p0与mysql驱动jar也要导入

    //创建QueryRunner对象

    //使用query方法执行select语句

    //使用ResultSetHandler封装结果集

    //使用DbUtils类释放资源

    C3P0Utils:

    package com.itheima.util;
    
    import java.beans.PropertyVetoException;
    import java.sql.Connection;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    
    import javax.sql.DataSource;
    
    import com.mchange.v2.c3p0.ComboPooledDataSource;
    
    public class C3P0Util {
        //得到一个数据源
        private static DataSource dataSource = new ComboPooledDataSource();
        
        
        public static DataSource getDataSource() {
            return dataSource;
        }
    
        //从数据源中得到一个连接对象
        public static Connection getConnection(){
            try {
                return dataSource.getConnection();
            } catch (SQLException e) {
                throw new RuntimeException("服务器错误");
            }
        }
        
        public static void release(Connection conn,Statement stmt,ResultSet rs){
            //关闭资源
                    if(rs!=null){
                        try {
                            rs.close();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        rs = null;
                    }
                    if(stmt!=null){
                        try {
                            stmt.close();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        stmt = null;
                    }
                    if(conn!=null){
                        try {
                            conn.close();//关闭
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        conn = null;
                    }
        }
        
    }

     c3p0-config.xml:

    <?xml version="1.0" encoding="UTF-8"?>
    <c3p0-config>
      <default-config>
        <property name="driverClass">com.mysql.jdbc.Driver</property>
        <property name="jdbcUrl">jdbc:mysql://localhost:3306/day06</property>
        <property name="user">root</property>
        <property name="password">abc</property>
        <property name="initialPoolSize">10</property>
        <property name="maxIdleTime">30</property>
        <property name="maxPoolSize">100</property>
        <property name="minPoolSize">10</property>
    
      </default-config>
    
      
    
    </c3p0-config>

    User:

    package com.itheima.entity;
    
    import java.util.Date;
    
    public class User {
        private int id;
        private String name;
        private String password;
        private String email;
        private Date birthday;
        public int getId() {
            return id;
        }
        public void setId(int id) {
            this.id = id;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public String getPassword() {
            return password;
        }
        public void setPassword(String password) {
            this.password = password;
        }
        public String getEmail() {
            return email;
        }
        public void setEmail(String email) {
            this.email = email;
        }
        public Date getBirthday() {
            return birthday;
        }
        public void setBirthday(Date birthday) {
            this.birthday = birthday;
        }
        @Override
        public String toString() {
            return "User [id=" + id + ", name=" + name + ", password=" + password
                    + ", email=" + email + ", birthday=" + birthday + "]";
        }
        
        
    
    }
    Test:
    TestSelect:
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.util.ArrayList;
    import java.util.List;
    
    import org.apache.commons.dbutils.QueryRunner;
    import org.apache.commons.dbutils.ResultSetHandler;
    import org.apache.commons.dbutils.handlers.BeanListHandler;
    import org.junit.Test;
    
    import com.itheima.entity.User;
    import com.sun.org.apache.bcel.internal.generic.ARRAYLENGTH;
    
    public class TestSelect {
        
        @Test
        public void testSelect() throws SQLException{
            //创建一个QueryRunner对象
            QueryRunner qr = new QueryRunner(C3P0Util.getDataSource());
            List<User> list = qr.query("select * from users", new ResultSetHandler<List<User>>(){
                //当query方法执行select语句后,将结果集以参数的形式传递过来
                public List<User> handle(ResultSet rs) throws SQLException {
                    List<User> list  = new ArrayList<User>();
                    while(rs.next()){
                        User u = new User();
                        u.setId(rs.getInt(1));
                        u.setName(rs.getString(2));
                        u.setPassword(rs.getString(3));
                        u.setEmail(rs.getString(4));
                        u.setBirthday(rs.getDate(5));
                        list.add(u);
                    }
                    return list;
                }
                
            });
            
            for (User user : list) {
                System.out.println(user);
            }
        }
        
        
        @Test
        public void testSelect2() throws SQLException{
            //创建一个QueryRunner对象
            QueryRunner qr = new QueryRunner(C3P0Util.getDataSource());
            //执行查询语句,并返回结果
            List<User> list = qr.query("select * from users where id=? and username=?", new BeanListHandler<User>(User.class),8,"jerry");
            //把结果集封装到了user中
            for (User user : list) {
                System.out.println(user);
            }
        }
    }

    TestCRUD:

    import java.sql.SQLException;
    import java.util.Date;
    
    import org.apache.commons.dbutils.QueryRunner;
    import org.junit.Test;
    
    public class TestCRUD {
        @Test
        public void testInsert() throws SQLException{
            //创建一个QueryRunner对象
            QueryRunner qr = new QueryRunner(C3P0Util.getDataSource());
            //执行sql语句
            qr.update("insert into users(username,password,email,birthday) values(?,?,?,?)", "菜10","123","c10@163.com",new Date());
            
        }
        
        @Test
        public void testUpdate() throws SQLException{
            //创建一个QueryRunner对象
            QueryRunner qr = new QueryRunner(C3P0Util.getDataSource());
            qr.update("update users set username=?,password=? where id=?", "周杰杰","333",15);
        }
        
        
        @Test
        public void testDelete() throws SQLException{
            //创建一个QueryRunner对象
            QueryRunner qr = new QueryRunner(C3P0Util.getDataSource());
            qr.update("delete from users where id=?", 15);
        }
        
        @Test//批处理,只能执行相同的sql语句
        public void testBatch() throws SQLException{
            //创建一个QueryRunner对象
            QueryRunner qr = new QueryRunner(C3P0Util.getDataSource());
            
            Object[][] params = new Object[10][];//高维代表执行多少次sql语句
            for (int i = 0; i < params.length; i++) {
                params[i] = new Object[]{"菜10"+i,"123","c10@163.com",new Date()};//给每次执行的sql语句中的?赋值
            }
            qr.batch("insert into users(username,password,email,birthday) values(?,?,?,?)", params );
            
        }
    }

    TestResultSetHandler:

    import java.sql.SQLException;
    import java.util.List;
    import java.util.Map;
    
    import org.apache.commons.dbutils.QueryRunner;
    import org.apache.commons.dbutils.handlers.ArrayHandler;
    import org.apache.commons.dbutils.handlers.ArrayListHandler;
    import org.apache.commons.dbutils.handlers.BeanHandler;
    import org.apache.commons.dbutils.handlers.BeanListHandler;
    import org.apache.commons.dbutils.handlers.ColumnListHandler;
    import org.apache.commons.dbutils.handlers.KeyedHandler;
    import org.apache.commons.dbutils.handlers.MapHandler;
    import org.apache.commons.dbutils.handlers.MapListHandler;
    import org.apache.commons.dbutils.handlers.ScalarHandler;
    import org.junit.Test;
    
    import com.itheima.entity.User;
    
    public class TestResultSetHandler {
        @Test//ArrayHandler:适合取1条记录。把该条记录的每列值封装到一个数组中Object[]
        public void tese1() throws SQLException{
            QueryRunner qr = new QueryRunner(C3P0Util.getDataSource());
            Object[] arr  = qr.query("select * from users", new ArrayHandler());
            
            for (Object o : arr) {
                System.out.println(o);
            }
        }
        
        @Test//ArrayListHandler:适合取多条记录。把每条记录的每列值封装到一个数组中Object[],把数组封装到一个List中
        public void tese2() throws SQLException{
            QueryRunner qr = new QueryRunner(C3P0Util.getDataSource());
            List<Object[]> query = qr.query("select * from users", new ArrayListHandler());
            
            for (Object[] os : query) {
                for (Object o : os) {
                    System.out.println(o);
                }
                System.out.println("--------------");
            }
        }
        
        @Test //ColumnListHandler:取某一列的数据。封装到List中。
        public void tese3() throws SQLException{
            QueryRunner qr = new QueryRunner(C3P0Util.getDataSource());
            List<Object> list = qr.query("select username,password from users", new ColumnListHandler(1));
            
            for (Object o : list) {
                System.out.println(o);
            }
        }
        
        @Test //KeyedHandler:取多条记录,每一条记录封装到一个Map中,再把这个Map封装到另外一个Map中,key为指定的字段值。
        public void tese4() throws SQLException{
            QueryRunner qr = new QueryRunner(C3P0Util.getDataSource());
            //大Map的key是表中的某列数据,小Map中的key是表的列名,所以大Map的key是Object类型,小Map的key是String类型
            Map<Object,Map<String,Object>> map = qr.query("select * from users", new KeyedHandler(1));
            
            for (Map.Entry<Object, Map<String,Object>> m : map.entrySet()) {
                System.out.println(m.getKey());//大Map中key值就是id列的值
                for (Map.Entry<String, Object> mm : m.getValue().entrySet()) {
                    System.out.println(mm.getKey()+"	"+mm.getValue());//取出小Map中的列名和列值
                }
                System.out.println("---------------------");
            }
            
        }
        
        
        @Test//MapHandler:适合取1条记录。把当前记录的列名和列值放到一个Map中
        public void tese5() throws SQLException{
            QueryRunner qr = new QueryRunner(C3P0Util.getDataSource());
            Map<String,Object> map = qr.query("select * from users where id=?", new MapHandler(),20);
            
            for (Map.Entry<String, Object> m : map.entrySet()) {
                System.out.println(m.getKey()+"	"+m.getValue());
            }
            
        }
        
        
        @Test//MapListHandler:适合取多条记录。把每条记录封装到一个Map中,再把Map封装到List中
        public void tese6() throws SQLException{
            QueryRunner qr = new QueryRunner(C3P0Util.getDataSource());
            List<Map<String,Object>> list = qr.query("select * from users", new MapListHandler());
            
            for (Map<String, Object> map : list) {
                for (Map.Entry<String, Object> m : map.entrySet()) {
                    System.out.println(m.getKey()+"	"+m.getValue());
                }
                System.out.println("---------------");
            }
        }
        
        @Test //ScalarHandler:适合取单行单列数据
        public void tese7() throws SQLException{
            QueryRunner qr = new QueryRunner(C3P0Util.getDataSource());
            Object o = qr.query("select count(*) from users", new ScalarHandler(1));
            System.out.println(o.getClass().getName());
        }
        
        @Test //BeanHandler:适合取单行单列数据
        public void tese8() throws SQLException{
            QueryRunner qr = new QueryRunner(C3P0Util.getDataSource());
            User user = qr.query("select * from users where id=?", new BeanHandler<User>(User.class),1);
            System.out.println(user);
        }
        
        
        @Test //BeanListHandler 
        public void tese9() throws SQLException{
            QueryRunner qr = new QueryRunner(C3P0Util.getDataSource());
            List<User> list = qr.query("select * from users where id=?", new BeanListHandler<User>(User.class),1);
            
            System.out.println(list.size());
        }
    }

    KeyedHandler:

    转载自: https://blog.csdn.net/CSDN_GIA/article/details/54137732

  • 相关阅读:
    Jenkins pipeline基本结构
    接口测试框架httprunner使用自定义extentreports报告模板遇到的问题小结
    python3中扩展字典类实现用点访问属性
    python3系列五可迭代对象、迭代器和生成器
    vue.js-组件嵌套
    使用Vue-CLI3.x进行vue.js环境搭建
    python系列四反射机制
    vue.js环境搭建踩坑记
    python系列三推导式
    python系列二filter()、map()和reduce()
  • 原文地址:https://www.cnblogs.com/YangGC/p/8693706.html
Copyright © 2011-2022 走看看