java——数据库——commons-DbUtils

Apache Commons DbUtils Tutorial

The Apache Commons DbUtils library is a small set of classes designed to make working with JDBC easier. JDBC resource cleanup code is mundane, error prone work so these classes abstract out all of the cleanup tasks from your code leaving you with what you really wanted to do with JDBC in the first place: query and update data.

Advantages of Using DbUtils are:

  1. No possibilities for resource leak.
  2. Cleaner, clearer persistence code. The amount of code needed to persist data in a database is drastically reduced.
  3. Automatically populate JavaBean properties from ResultSets. You don’t need to manually copy column values into bean instances by calling setter methods. Each row of the ResultSet can be represented by one fully populated bean instance.

The main classes used from this DbUtils library are DbUtils, QueryRunner and the ResultSetHandler.

DbUtils: A collection of JDBC helper methods, all the methods in this class are static, and this class is a thread safe means multiple threads can access concurrently.

ResultSetHandler: It is an interface, implementations of this interface convert ResultSets into other objects.

  1. BeanHandler: It converts the ResultSet row into a JavaBean.
  2. MapHandler: It converts the ResultSet row into a Map.
  3. BeanListHandler: It converts a ResultSet into a List of beans. etc

QueryRunner: Executes SQL queries with pluggable strategies for handling ResultSets. This class is thread safe.

Simple example to use DbUtils, QueryRunner and ResultSetHandler:

1. The User table, here is the script to create the database table and inserting the data into the User table.

CREATE TABLE IF NOT EXISTS `user` (
  `userId` int(11) NOT NULL AUTO_INCREMENT,
  `firstName` varchar(50) NOT NULL,
  `lastName` varchar(50) NOT NULL,
  `phoneNo` varchar(50) NOT NULL,
  `emailId` varchar(50) NOT NULL,
  PRIMARY KEY (`userId`)
) ENGINE=InnoDB;

INSERT INTO `user` (`userId`, `firstName`, `lastName`, `phoneNo`, `emailId`) VALUES
(1, ‘Pramod‘, ‘Ganta‘, ‘9889885566‘, ‘[email protected]‘),
(2, ‘Suman‘, ‘Manthena‘, ‘8858863456‘, ‘[email protected]‘),
(3, ‘Prakash‘, ‘Puli‘, ‘9889885566‘, ‘[email protected]‘),
(4, ‘Rohit‘, ‘Sunkari‘, ‘8858863456‘, ‘[email protected]‘);

2. The Java Bean class representing the User table. The property name are same as the column names in User table.

package db.utisl2;

public class User {
    private String userId;
    private String firstName;
    private String lastName;
    private String phoneNO;
    private String emailId;

    public User() {
    }

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getPhoneNO() {
        return phoneNO;
    }

    public void setPhoneNO(String phoneNO) {
        this.phoneNO = phoneNO;
    }

    public String getEmailId() {
        return emailId;
    }

    public void setEmailId(String emailId) {
        this.emailId = emailId;
    }
}

3. In this example class using BeanHandler which is the implementation of the ResultSetHandler interface, and it returns the ResultSet into a Java Bean Object.

package db.utisl2;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

public class DbUtilsBeanHandler {
    public static void main(String[] args) {
        Connection conn = null;
        String url = "jdbc:mysql://localhost:3306/test";
        String driver = "com.mysql.jdbc.Driver";
        String usr = "root";
        String pwd = "root";
        User user = null;
        try {
            // Loading the Driver using DbUtils static method
            DbUtils.loadDriver(driver);
            conn = DriverManager.getConnection(url, usr, pwd);
            QueryRunner query = new QueryRunner();
            user = query.query(conn, "select * from user where userId=3", new BeanHandler<User>(
                    User.class));
            // query.query
            System.out.println("User Object::  " + user.getUserId() + "\t" + user.getFirstName()
                    + "\t" + user.getLastName() + "\t" + user.getEmailId());

        } catch (SQLException se) {
            se.printStackTrace();
        } finally {
            // Closing the connection quietly, means it will handles the
            // SQLException
            DbUtils.closeQuietly(conn);
        }
    }
}

Output:

User Object::  3    Prakash    Puli

4. In this example class using BeanListHandler which also the implementation of the ResultSetHandler interface, and it returns the ResultSet into a List of Java Bean Objects.

package db.utisl2;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.List;
import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

public class DbUtilsBeanListHandler {

    public static void main(String[] args) {
        Connection conn = null;
        String url = "jdbc:mysql://localhost:3306/test";
        String driver = "com.mysql.jdbc.Driver";
        String user = "root";
        String pwd = "root";
        List<User> users = null;
        try {
            DbUtils.loadDriver(driver);
            conn = DriverManager.getConnection(url, user, pwd);
            QueryRunner query = new QueryRunner();
            users = query.query(conn, "select * from user", new BeanListHandler<User>(User.class));
            for (int i = 0; i < users.size(); i++) {
                User bean = users.get(i);
                System.out.println("User Objects::  " + bean.getUserId() + "\t"
                        + bean.getFirstName() + "\t" + bean.getLastName() + "\t"
                        + bean.getEmailId());
            }
        } catch (SQLException se) {
            se.printStackTrace();
        } finally {
            DbUtils.closeQuietly(conn);
        }
    }
}

Output:

User Objects::  1    Pramod    Ganta        pramod@codesuggestions.com
User Objects::  2    Suman    Manthena    suman@codesuggestions.com
User Objects::  3    Prakash    Puli        prakash@codesuggestions.com
User Objects::  4    Rohit    Sunkari        rohit@codesuggestions.com

5. In this example class using MapListHandler which also the implementation of the ResultSetHandler interface, and it returns the ResultSet into a List of Map Objects. The Map object contains the each row, the column name as key and value as value in the Map object.

package db.utisl2;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.MapListHandler;

public class DbUtilsMapListHandler {

    public static void main(String[] args) {
        Connection conn = null;
        String url = "jdbc:mysql://localhost:3306/test";
        String driver = "com.mysql.jdbc.Driver";
        String user = "root";
        String pwd = "root";
        try {
            DbUtils.loadDriver(driver);
            conn = DriverManager.getConnection(url, user, pwd);
            QueryRunner query = new QueryRunner();
            List<Map<String, Object>> mapList = query.query(conn, "select * from user",
                    new MapListHandler());
            for (int i = 0; i < mapList.size(); i++) {
                Map<String, Object> map = mapList.get(i);
                System.out.println("------> " + map.get("userId") + "\t" + map.get("firstName")
                        + "\t" + map.get("emailId"));
            }
        } catch (SQLException se) {
            se.printStackTrace();
        } finally {
            DbUtils.closeQuietly(conn);
        }
    }
}

Output:

------> 1    Pramod    [email protected]
------> 2    Suman    [email protected]
------> 3    Prakash    [email protected]
------> 4    Rohit    [email protected]

Note: When we fetching from the Map, if we give the wrong column name it ruturn null value. Ex: map.get("fistName"), here mispelling the firstName. The same with BeanHandler to, if the Bean properties and table columns are not in match, it will return null values.

时间: 2024-10-05 22:15:55

java——数据库——commons-DbUtils的相关文章

java.lang.ClassNotFoundException: org.apache.commons.dbutils.QueryRunner

七月 28, 2017 11:06:33 下午 org.apache.catalina.core.StandardWrapperValve invoke严重: Servlet.service() for servlet [com.itheima.transfer.web.TransferServlet] in context with path [/WEB19] threw exception [Servlet execution threw an exception] with root ca

Java连接数据库 #04# Apache Commons DbUtils

索引 通过一个简单的调用看整体结构 Examples 修改JAVA连接数据库 #03# HikariCP中的代码 DbUtils并非是什么ORM框架,只是对原始的JDBC进行了一些封装,以便我们少写一些重复代码.就“用”而言,仅仅需要学习QueryRunner类和ResultSetHandler接口就可以了.它的显著特点就是超级轻量级,总代码量目测似乎还不到一万行. 通过一个简单的调用看整体结构 public class TestDbUtils { private static final Qu

数据库工具--DBUtils工具类的使用

1. DBUtils概述 DBUtils 是 JDBC的一个简化开发工具包.使用DBUtils需要导入的jar包:commons-dbutils-1.4.jar 核心类:QueryRunner 包 org.apache.commons.dbutils java.lang.Object  |--org.apache.commons.dbutils.AbstractQueryRunner     |--org.apache.commons.dbutils.QueryRunner 构造方法: Quer

Apache Commons DbUtils

1       概述 Commons DBUtils类库是小型的设计于易于使用JDBC的类集合.JDBC资源清理是平凡的,容易出错,以至于这些类从你的代码中抽象出清理代码,剩下你最初真正想要使用JDBC做的代码:查询和更新数据. 使用DBUtils的一些优势: 没有资源泄露的可能性.正确的JDBC编码并不难,但它耗时且乏味.这常常会导致连接泄漏可能很难追踪. 清晰的持久化代码.需要持久化数据到数据库中的代码大幅减少.剩下的代码清晰的表达你的意图没有凌乱的资源清理. 从ResultSet自动填充J

高性能jdbc封装工具 Apache Commons DbUtils 1.6

转载自原文地址:http://gao-xianglong.iteye.com/blog/2166444 前言 关于Apache的DbUtils中间件或许了解的人并不多,大部分开发人员在生成环境中更多的是依靠Hibernate.Ibatis.Spring JDBC.JPA等大厂提供的持久层技术解决方案,或者是企业内部自己研发的持久层技术.但无论如何,使用这些技术的初衷和本质都是为了能够减少企业开发成本,提高生产效率,降低耦合. 放眼企业级项目,Hibernate等ORM产品是首选,而互联网领域,大

高性能jdbc封装工具 Apache Commons DbUtils 1.6(转载)

转载自原文地址:http://gao-xianglong.iteye.com/blog/2166444 前言 关于Apache的DbUtils中间件或许了解的人并不多,大部分开发人员在生成环境中更多的是依靠Hibernate.Ibatis.Spring JDBC.JPA等大厂提供的持久层技术解决方案,或者是企业内部自己研发的持久层技术.但无论如何,使用这些技术的初衷和本质都是为了能够减少企业开发成本,提高生产效率,降低耦合. 放眼企业级项目,Hibernate等ORM产品是首选,而互联网领域,大

Commons - dbutils

时间:2016-12-4 18:06 --基本类 自己写的JDBC小工具: public class JDBCUtils { // 使用的是配置文件的默认配置,即必须给出c3p0-config.xml配置文件 private static ComboPooledDataSource dataSource = new ComboPooledDataSource(); /* * 使用连接池返回一个连接对象 */ public static Connection getConnection() thr

Apache Commons DbUtils使用手册

Apache Commons DbUtils使用手册 作者:chszs,转载需注明.博客主页:http://blog.csdn.net/chszs 一.介绍 DBUtils是个小巧的JDBC轻量级封装的工具包,其最核心的特性是在JDBC的基础上做了一层封装,主要是对结果集的封装,可以直接将查询出来的结果集封装成JavaBean,旨在简化JDBC代码混乱与重复.JDBC代码开发,存在很多难点:1)操作过程复杂,代码操作一个模式,大量的重复.2)结果集难以处理.3)到处都强制检查SQLExcepti

JAVA数据库编程(JDBC技术)-入门笔记

本菜鸟才介入Java,我现在不急着去看那些基本的语法或者一些Java里面的版本的特征或者是一些晋级的知识,因为有一点.Net的OOP编程思想,所以对于Java的这些语法以及什么的在用到的时候在去发现学习一下.我现在很迫不及待用JAVA想来实现以下对数据库的增删改查.想实现就来看Java是怎么操作数据库的,回想下.Net里你可能会配置web.Config,或者你去写一些DBhelper类然后调用里面的自己定义的一些增删改查的方法,更或者你去配一些数据控件等等往往发现操作基本都是一体化的简单.现在面