Commons-dbutils框架

Posted IT-老牛

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Commons-dbutils框架相关的知识,希望对你有一定的参考价值。

文章目录

1. Commons-dbutils简介

commons-dbutilsApache 组织提供的一个开源 JDBC工具类库,它是对JDBC的简单封装,学习成本极低,并且使用dbutils能极大简化jdbc编码的工作量,同时也不会影响程序的性能。

API介绍

org.apache.commons.dbutils.QueryRunner
org.apache.commons.dbutils.ResultSetHandler

工具类

org.apache.commons.dbutils.DbUtils

2.QueryRunner类使用讲解

该类简单化了SQL查询,它与ResultSetHandler组合在一起使用可以完成大部分的数据库操作,能够大大减少编码量。

QueryRunner类提供了两个构造方法:

  • 默认的构造方法
  • 需要一个 javax.sql.DataSource 来作参数的构造方法。

2.1.QueryRunner类的主要方法

  • public Object query(Connection conn, String sql, Object[] params, ResultSetHandler rsh) throws SQLException:执行一个查询操作,在这个查询中,对象数组中的每个元素值被用来作为查询语句的置换参数。该方法会自行处理 PreparedStatementResultSet 的创建和关闭。

  • public Object query(String sql, Object[] params, ResultSetHandler rsh) throws SQLException: 几乎与第一种方法一样;唯一的不同在于它不将数据库连接提供给方法,并且它是从提供给构造方法的数据源(DataSource) 或使用的setDataSource 方法中重新获得 Connection

  • public Object query(Connection conn, String sql, ResultSetHandler rsh) throws SQLException : 执行一个不需要置换参数的查询操作。

  • public int update(Connection conn, String sql, Object[] params) throws SQLException:用来执行一个更新(插入、更新或删除)操作。

  • public int update(Connection conn, String sql) throws SQLException:用来执行一个不需要置换参数的更新(插入、更新或删除)操作。

2.2.使用QueryRunner类实现CRUD

2.2.1.JdbcUtils

jdbc.properties

# key=value
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/singerdb?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&useSSL=false
jdbc.username=root
jdbc.password=123456

JdbcUtils

package com.bruce.utils;

import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class JdbcUtils 

    private static String driver = null;
    private static String url = null;
    private static String username = null;
    private static String password = null;

    static 
        try 
            //读取db.properties文件中的数据库连接信息
            InputStream in = JdbcUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");
            Properties prop = new Properties();
            prop.load(in);
            //获取数据库连接驱动
            driver = prop.getProperty("jdbc.driverClassName");
            //获取数据库连接URL地址
            url = prop.getProperty("jdbc.url");
            //获取数据库连接用户名
            username = prop.getProperty("jdbc.username");
            //获取数据库连接密码
            password = prop.getProperty("jdbc.password");
            //加载数据库驱动
            Class.forName(driver);
         catch (Exception e) 
            throw new ExceptionInInitializerError(e);
        
    

    /**
     * @return Connection数据库连接对象
     * @throws SQLException
     * @Method: getConnection
     * @Description: 获取数据库连接对象
     */
    public static Connection getConnection() throws SQLException 
        return DriverManager.getConnection(url, username, password);
    

    /**
     * @param conn
     * @param st
     * @param rs
     * @Method: release
     * @Description: 释放资源,
     * 要释放的资源包括Connection数据库连接对象,负责执行SQL命令的Statement对象,存储查询结果的ResultSet对象
     */
    public static void release(Connection conn, Statement st, ResultSet rs) 
        try 
            if (rs != null) 
                //关闭存储查询结果的ResultSet对象
                rs.close();
            
            if (st != null) 
                //关闭负责执行SQL命令的Statement对象
                st.close();
            
            if (conn != null) 
                //关闭Connection数据库连接对象
                conn.close();
            
         catch (SQLException e) 
            e.printStackTrace();
        
    

2.2.2.RunnerCRUDTest

maven依赖:

 <!--导入dbutils包-->
 <dependency>
     <groupId>commons-dbutils</groupId>
     <artifactId>commons-dbutils</artifactId>
     <version>1.6</version>
 </dependency>

测试表:

 -- 测试表
 create table users(
     id int primary key auto_increment,
     name varchar(40),
     password varchar(40),
     email varchar(60),
     birthday date
 );
package com.bruce.test;

import com.bruce.pojo.Users;
import com.bruce.utils.JdbcUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.junit.Test;

import java.sql.SQLException;
import java.util.Date;
import java.util.List;

public class QueryRunnerCRUDTest 

    @Test
    public void add() throws SQLException 
        //将数据源传递给QueryRunner,QueryRunner内部通过数据源获取数据库连接
        QueryRunner qr = new QueryRunner();
        String sql = "insert into users(name,password,email,birthday) values(?,?,?,?)";
        Object params[] = "tom", "123", "bruce@sina.com", new Date();
        qr.update(JdbcUtils.getConnection(), sql, params);
    

    @Test
    public void delete() throws SQLException 
        QueryRunner qr = new QueryRunner();
        String sql = "delete from users where id=?";
        qr.update(JdbcUtils.getConnection(), sql, 1);
    

    @Test
    public void update() throws SQLException 
        QueryRunner qr = new QueryRunner();
        String sql = "update users set name=? where id=?";
        Object params[] = "ddd", 5;
        qr.update(JdbcUtils.getConnection(), sql, params);
    

    @Test
    public void find() throws SQLException 
        QueryRunner qr = new QueryRunner();
        String sql = "select * from users where id=?";
        Object params[] = 2;
        Users user = (Users) qr.query(JdbcUtils.getConnection(), sql, params, new BeanHandler(Users.class));
        System.out.println(user);
    

    @Test
    public void getAll() throws SQLException 
        QueryRunner qr = new QueryRunner();
        String sql = "select * from users";
        List<Users> list = (List) qr.query(JdbcUtils.getConnection(),sql, new BeanListHandler(Users.class));
        System.out.println(list);
    


3.DButis整合Druid数据库连接池

Druid(德鲁伊)是阿里巴巴开发的号称为监控而生的数据库连接池,Druid是目前最好的数据库连接池。在功能、性能、扩展性方面,都超过其他数据库连接池,同时加入了日志监控,可以很好的监控DB池连接和SQL的执行情况。

  <!--导入druid数据库连接池-->
  <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>1.1.10</version>
  </dependency>

jdbc.properties配置类

# key=value
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/singerdb?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&useSSL=false
username=root
password=123456
filters=stat
initialSize=2
maxActive=300
maxWait=60000

timeBetweenEvictionRunsMillis=60000
minEvictableIdleTimeMillis=300000
validationQuery=SELECT 1
testWhileIdle=true
testOnBorrow=false
testOnReturn=false
poolPreparedStatements=false
maxPoolPreparedStatementPerConnectionSize=200

参数说明:

package com.bruce.utils;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

import javax.sql.DataSource;

import com.alibaba.druid.pool.DruidDataSourceFactory;


public class JdbcUtils 

    private static Properties properties = null;
    private static DataSource dataSource = null;

    private volatile static JdbcUtils instatce = null;
    private Connection connection = null;

    //私有构造函数,防止实例化对象
    private JdbcUtils() 

    

    static 
        try 
            properties = new Properties();
            // 1.加载properties文件
            InputStream is = JdbcUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");
            // 2.加载输入流
            properties.load(is);
            // 3.获取数据源
            dataSource = getDatasource();
         catch (IOException e) 
            e.printStackTrace();
        
    

    /**
     * 用简单单例模式确保只返回一个链接对象
     *
     * @return
     */
    public static JdbcUtils getInstace() 
        if (instatce == null) 
            synchronized (JdbcUtils.class) 
                if (instatce == null) 
                    instatce = new JdbcUtils();
                
            
        
        return instatce;
    

    // 返回一个数据源
    public DataSource getDataSource() 
        return dataSource;
    

    // 返回一个链接
    public Connection getConnection() 
        try 
            connection = dataSource.getConnection();
         catch (SQLException e) 
            e.printStackTrace();
        
        return connection;
    

    // 加载数据源
    public static DataSource getDatasource() 
        DataSource source = null;
        try 
            source = DruidDataSourceFactory.createDataSource(properties);
         catch (Exception e) 
            e.printStackTrace();
        
        return source;
    

4.改造QueryRunnerCRUDTest

DruidUtils

package com.bruce.utils;

import java.sql.Connection;
import java.sql.SQLException;

import javax.sql.DataSource;

public class DruidUtils 

    private static Connection connection = null;

    //获取元数据
    public static DataSource getDatasource() 
        DataSource dataSource = JdbcUtils.getInstace().getDataSource();
        return dataSource;
    

    //获取链接
    public static Connection getConnection() 
        connection = JdbcUtils.getInstace().getConnection();
        return connection;
    

    //归还资源
    public void release() 
        try 
            if (connection != null) 
                connection.close();
            
         catch (SQLException e) 
            e.printStackTrace();
        
    


package com.bruce.test;

import com.bruce.pojo.Users;
import com.bruce.utils.JdbcUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.junit.Test;

import java.sql.SQLException;
import java.util.Date;
import java.util.List;

public class QueryRunnerCRUDTest 


    //将数据源传递给QueryRunner,QueryRunner内部通过数据源获取数据库连接
    QueryRunner qr = new QueryRunner(DruidUtils.getDataSource());

    @Test
    public void add() throws SQLException 
        String sql = "insert into users(name,password,email,birthday) values(?,?,?,?)";
        Object params[] = "tom", "123", "bruce@sina.com", new Date();
        qr.update(sql, params);
    

    @Test
    public void delete() throws SQLException 
        String sql = "delete from users where id=?";
        qr.update(sql, 1);
    

    @Test
    public void update() throws SQLException 
        String sql = "update users set name=? where id=?";
        Object params[] = "ddd", 5;
        qr.update(sql, params);
    

    @Test
    public void find() throws SQLException 
        String sql = "select * from users where id=?";
        Object params[] = 2;
        Users user = (Users) qr.query(sql, new BeanHandler(Users.class), params);
        System.out.println(user);
    

    @Test
    public void getAll() throws SQLException 
        String sql = "select * from users";
        List<Users> list = (List) qr.query(sql, new BeanListHandler(Java学习笔记49(DBUtils工具类二)

Apache的DBUtils框架学习

javaweb学习总结—Apache的DBUtils框架学习

javaweb学习总结—Apache的DBUtils框架学习

泛型的使用:模拟写出commons-dbutils

commons-dbutils学习——QueryRunner类和ResultSetHandler接口介绍