• DBUtils框架编程步骤


    JDBC元数据API :是框架编写的基础,掌握元数据API ,更清楚知道框架是如何实现的

    元数据MetaData : 指数据库中 库、表、列的定义信息
    1、DataBaseMetaData 数据库元数据
    2、ParameterMetaData 参数元数据
    3、ResultSetMetaData 结果集元数据

    上面的元数据可以不必太深入了解,只需要知道DBUtils框架是使用该API实现的就可以了

    ------------------------------------------------------------------------------------------------------------------------------------------------

    DBUtils学习
    1、QueryRunner 框架核心类 ,所有数据库操作都是必须通过 QueryRunner 进行的
    2、ResultSetHandler 结果集封装接口,完成将ResultSet 结果集 封装为一个Java对象
    3、DbUtils 工具类 提供驱动管理、事务管理、释放资源等一系列公共方法

    去官网下载DBUtils
    将dbutils的jar 复制 WEB-INF/lib

    QueryRunner 与 ResultSetHandler 一起使用,完成数据表增删改查
    构造器:
    QueryRunner() -------- 没有传递连接池给DBUtils 框架,框架不能获得数据库连接,接下来每个操作,必须将数据库连接传给框架 (手动管理事务)
    QueryRunner(DataSource ds) ---- 将连接池给DBUtils框架,以后每个操作,都会从连接池中获取一个新的连接 (每条SQL 一个单独的事务)

    更新操作 insert update delete
    public int update(Connection conn, String sql, Object... params) ---- 手动管理事务,没有将连接池提供框架,传入连接
    public int update(String sql, Object... params) ----- 将连接池交给框架,由框架管理事务,不需要传入连接
    查询操作 select
    public Object query(Connection conn, String sql, ResultSetHandler<T> rsh, Object... params)
    public Object query(String sql, ResultSetHandler<T> rsh, Object... params)

    1、需要手动管理事务
    QueryRunner()
    public int update(Connection conn, String sql, Object... params)
    query(Connection conn, String sql, ResultSetHandler<T> rsh, Object... params)

    2、由框架管理事务 (每条SQL都是一个单独事务)
    QueryRunner(DataSource ds)
    public int update(String sql, Object... params)
    public Object query(String sql, ResultSetHandler<T> rsh, Object... params)

    ResultSetHandler 在DBUtils 框架中提供九个默认 实现类,直接使用九个默认实现类,可以完成常规操作,而不需要自定义结果集封装
    1) ArrayHandler 和 ArrayListHandler 将数据表的每行记录保存Object[] 中
    2) BeanHandler 和 BeanListHandler 将数据表每行记录 保存JavaBean对象中
    * 封装javabean属性时,必须保证数据表列名与 javabean属性名一致,否则无法封装
    3) MapHandler和 MapListHandler 将结果每行记录保存到一个Map集合,key是列名,value是值
    4) ColumnListHandler 查询结果集中指定一列数据
    5) KeyedHandler(name) 结果集每行数据封装map,再将map存入另一个map 作为value,指定一列作为key
    6) ScalarHandler 进行单值查询 select count(*) from account;

    重点:BeanHandler 和 BeanListHandler 、ScalarHandler 、ColumnListHandler

    ------------------------------------------------------------------------------------------------------------------------------------------------

    编程步骤:

    导入jar包:

    mysql-connector-java-5.0.8-bin.jar commons-dbutils-1.4.jar c3p0-0.9.1.2.jar

    c3p0-config.xml :c3p0的配置文件,位于工程src目录下

    <?xml version="1.0" encoding="UTF-8"?>
    <c3p0-config>
        <default-config>
            <property name="user">root</property>
            <property name="password">root</property>
            <property name="driverClass">com.mysql.jdbc.Driver</property>
            <property name="jdbcUrl">jdbc:mysql:///day15?generateSimpleParameterMetadata=true</property>
        </default-config> <!-- This app is massive! -->
    </c3p0-config> 

    工具类(通过c3p0 建立连接和释放资源)

    package cn.itcast.utils;
    
    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;
    
    /**
     * 工具类 建立连接 释放资源
     * 
     * @author seawind
     * 
     */
    public class JDBCUtils {
        // 通过c3p0 数据库连接池 建立连接
        // 自动读取 src下 c3p0-config.xml 配置文件
        private static ComboPooledDataSource dataSource = new ComboPooledDataSource();
    
        public static DataSource getDataSource() {
            return dataSource;
        }
    
        public static Connection getConnection() throws SQLException {
            return dataSource.getConnection();
        }
    
        // 释放资源的方法 可以被 DBUtils框架 DbUtils工具类取代
        public static void release(ResultSet rs, Statement stmt, Connection conn) {
            // 释放资源
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
                rs = null;
            }
            release(stmt, conn);
        }
    
        public static void release(Statement stmt, Connection conn) {
            if (stmt != null) {
                try {
                    stmt.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
                stmt = null;
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
                conn = null;
            }
        }
    }

    DBUtilsTest:对数据库的CRUD操作

    package cn.itcast.dbutils;
    
    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.junit.Test;
    
    import cn.itcast.domain.Account;
    import cn.itcast.utils.JDBCUtils;
    
    /**
     * 调用DBUtils框架完成增删改查
     * 
     * @author seawind
     * 
     */
    public class DBUtilsTest {
        @Test
        // 查询
        public void testSelect() throws SQLException {
            QueryRunner queryRunner = new QueryRunner(JDBCUtils.getDataSource());
    
            // 自定义结果集封装
            List<Account> accounts = queryRunner.query("select * from account",
                    new ResultSetHandler<List<Account>>() {
                        @Override
                        public List<Account> handle(ResultSet rs)
                                throws SQLException {
                            List<Account> accounts = new ArrayList<Account>();
                            try {
                                while (rs.next()) {
                                    Account account = new Account();
                                    account.setId(rs.getInt("id"));
                                    account.setName(rs.getString("name"));
                                    account.setMoney(rs.getDouble("money"));
    
                                    accounts.add(account);
                                }
                                return accounts;
                            } catch (SQLException e) {
                                e.printStackTrace();
                                throw new RuntimeException(e);
                            }
                        }
                    });
    
            for (Account account : accounts) {
                System.out.println(account.getName() + "," + account.getMoney());
            }
        }
    
        @Test
        // 删除
        public void testDelete() throws SQLException {
            QueryRunner queryRunner = new QueryRunner(JDBCUtils.getDataSource());
            queryRunner.update("delete from account where name =?", "ddd");
        }
    
        @Test
        // 修改 Account 数据
        public void testUpdate() throws SQLException {
            QueryRunner queryRunner = new QueryRunner(JDBCUtils.getDataSource());
            queryRunner.update("update account set name=?,money=? where id =?",
                    "小明", 3000, 2);
        }
    
        @Test
        // 插入Account表数据
        public void testInsert() throws SQLException {
            // 创建QueryRunner对象
            QueryRunner queryRunner = new QueryRunner(JDBCUtils.getDataSource());
            // 插入
            queryRunner.update("insert into account values(null,?,?)", "eee", 1000);
        }
    }

    DBUtils九个内置Handler(结果集处理)

    package cn.itcast.dbutils;
    
    import java.sql.SQLException;
    import java.util.Arrays;
    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 cn.itcast.domain.Account;
    import cn.itcast.utils.JDBCUtils;
    
    /**
     * 使用 DBUtils 九个内置handler
     * 
     * @author seawind
     * 
     */
    public class ResultSetHandlerTest {
        // ScalarHandler
        @Test
        public void testScalarHandler() throws SQLException {
            QueryRunner queryRunner = new QueryRunner(JDBCUtils.getDataSource());
            long value = (Long) queryRunner.query("select count(*) from account",
                    new ScalarHandler(1));
    
            System.out.println(value);
        }
    
        @Test
        // KeyedHandler
        public void testKeyedHandler() throws SQLException {
            QueryRunner queryRunner = new QueryRunner(JDBCUtils.getDataSource());
            Map<Object, Map<String, Object>> map = queryRunner.query(
                    "select * from account", new KeyedHandler("id"));
            System.out.println(map);
        }
    
        // ColumnListHandler
        @Test
        public void testColumnListHandler() throws SQLException {
            QueryRunner queryRunner = new QueryRunner(JDBCUtils.getDataSource());
            List<Object> list = queryRunner.query("select * from account",
                    new ColumnListHandler("money"));
            System.out.println(list);
        }
    
        // MapListHandler
        @Test
        public void testMapListHandler() throws SQLException {
            // 每行---Map 很多行 ---List<Map>
            QueryRunner queryRunner = new QueryRunner(JDBCUtils.getDataSource());
            List<Map<String, Object>> list = queryRunner.query(
                    "select * from account", new MapListHandler());
            System.out.println(list);
        }
    
        // MapHandler
        @Test
        public void testMapHandler() throws SQLException {
            // 每行记录 保存Map集合
            QueryRunner queryRunner = new QueryRunner(JDBCUtils.getDataSource());
            Map<String, Object> map = queryRunner.query("select * from account",
                    new MapHandler());
    
            System.out.println(map);
        }
    
        // BeanListHandler
        @Test
        public void testBeanListHandler() throws SQLException {
            QueryRunner queryRunner = new QueryRunner(JDBCUtils.getDataSource());
            // 每行记录 --Account 很多行 --- List<Account>
            List<Account> accounts = queryRunner.query("select * from account",
                    new BeanListHandler<Account>(Account.class));
            for (Account account : accounts) {
                System.out.println(account.getId());
                System.out.println(account.getName());
                System.out.println(account.getMoney());
            }
        }
    
        // BeanHandler
        @Test
        public void testBeanHandler() throws SQLException {
            // 将第一行数据 --- java对象中
            QueryRunner queryRunner = new QueryRunner(JDBCUtils.getDataSource());
            // 泛型用来控制方法返回值,参数创建方法返回结果对象
            Account account = queryRunner.query("select * from account",
                    new BeanHandler<Account>(Account.class));
            System.out.println(account.getId());
            System.out.println(account.getName());
            System.out.println(account.getMoney());
        }
    
        // ArrayListHandler
        @Test
        public void testArrayListHandler() throws SQLException {
            QueryRunner queryRunner = new QueryRunner(JDBCUtils.getDataSource());
            // 每行是 Object[] ----- 很多行 List<Object[]>
            List<Object[]> list = queryRunner.query("select * from account",
                    new ArrayListHandler());
            for (Object[] objects : list) {
                System.out.println(Arrays.toString(objects));
            }
        }
    
        // ArrayHandler
        @Test
        public void testArrayHandler() throws SQLException {
            QueryRunner queryRunner = new QueryRunner(JDBCUtils.getDataSource());
            // 封装结果集第一行数据 ---- Object[]
            Object[] arr = queryRunner.query("select * from account",
                    new ArrayHandler());
            System.out.println(Arrays.toString(arr));
        }
    }

     扩展阅读:

    DBUtils – BeanProcessor扩展,支持自定义字段映射 - Iteam项目组 Smith&Wesson(史密斯威森) - 博客频道 - CSDN.NET

    扩展commons dbutils的JavaBean转换方式 - nighty - BlogJava

    Common Dbutils详解 - 指引前行 - 博客频道 - CSDN.NET

    Apache DBUtils使用总结 【转】 - 夜真寒 - 博客园

    DBUtils使用详解一 - luxiaoyu_sdc的专栏 - 博客频道 - CSDN.NET

    DBUtils使用详解二 - luxiaoyu_sdc的专栏 - 博客频道 - CSDN.NET

    DBUtils 增删改查例子 - OPEN 开发经验库

    Dbutils详解 - gaozhuang211 - BlogJava

    DBUtils – BeanProcessor扩展,支持自定义字段映射 - Iteam项目组 Smith&Wesson(史密斯威森) - 博客频道 - CSDN.NET

  • 相关阅读:
    Tomcat下bootstrap启动分析
    Ubuntu读取/root/.profile时发现错误:mesg:ttyname fa
    【转载】Activiti delete process definition by key
    Ubuntu16解锁root
    Activiti源码:ActivitiEventSupport类中eventListeners的设计
    [转载] Activiti Tenant Id 字段释疑
    Linux下使用NTFS格式移动硬盘
    Linux dd命令制作U盘启动盘
    Activiti源码:StandaloneInMemProcessEngineConfiguration与SpringProcessEngineConfiguration
    Activiti源码学习:ExecutionListener与TaskListener的区别
  • 原文地址:https://www.cnblogs.com/vaer/p/3903538.html
Copyright © 2020-2023  润新知