当前位置:网站首页>Jdbc-dbutils

Jdbc-dbutils

2022-06-09 05:57:00 qq_ thirty-seven million seven hundred and five thousand five h

1 brief introduction

DbUtils yes Apache The organization provides a solution to JDBC Open source tool class library for simple encapsulation , Using it can simplify JDBC Application development , At the same time, it will not affect the performance of the program . In brief, it is to simplify the database operation code in conjunction with the database connection pool , Database connection pooling simplifies connection operations , and DBUtils The operation of adding, deleting, modifying and querying is simplified , Bottom layer DbUtils Tool implementation , We just need to focus on usage and understand the implementation logic .

2 Common classes

DBUtils Tools
To make it easier to use JDBC,Apache The organization provides a tool class library commons-dbutils, It is a component that operates the database , Achieve a goal of JDBC Simple encapsulation , It can greatly simplify... Without affecting performance JDBC Ground coding workload .

API Introduce
commons-dbutils The core of is two classes org.apache.commons.DbUtils、org.apache.commons.dbutils.QueryRunner And an interface org.apache.commons.dbutils.ResultSetHealer.

DBUtils class
DBUtils Class is mainly used to close the connection 、 load JDBC Routine work such as drivers provides methods , The methods it provides are static methods .
1、close() Method
stay DBUtils Class , Provides three overloaded close() Method , These methods are used to close the data connection , And when the connection is closed , First, we will check whether the parameter is NULL, If not , The method will close Connection、Statement、ResultSet These three objects .
2、closeQuietly(Connection conn,Statement stmt,ResultSet rs) Method
This method is used to turn off Connection、Statement and ResultSet object . And close() Methods compared ,closeQuietly() Method can not only Connection、Statement and ResultSet The object is NULL Avoid closing if , You can also hide some of the things that are thrown out of the program SQL abnormal .
3、commitAndCloseQuietly(Connection conn) Method
commitAndCloseQuietly() Method to submit a connection , Then close the connection , And do not throw an exception when closing the connection .
4、loadDriver(java.lang.String driverClassName) Method
loadDriver() Method is used to load and register JDBC The driver , If you succeed, go back true. When this method is used , No need to capture ClassNotFoundException abnormal .

QueryRunner class
QueryRunner Class simplifies execution SQL Code for statement , It is associated with ResultSetHandler Together, you can complete most of the database operations , Greatly reduce the amount of coding .
QueryRunner Class provides two constructors , One is the default constructor , One is need javax.sql.DataSource As a construction method of parameters . So instead of providing a database connection for a method , Provided to the constructor DataSource Can be used to obtain a connection . however , In the use of JDBC When operating the database , Need to use Connection Object to operate on transactions ,QueryRunner Class provides different methods .

1、query(Connection conn,String sql,ResultSetHandler rsh,Object[] params) Method
This method is used to perform query operations , among , Parameters params Represents an array of objects , The value of each element in the array is used as the replacement parameter of the query statement . It should be noted that , This method automatically handles PreparedStatement and ResultSet Create and close .
It is worth mentioning that ,QueryRunner There is another method in query(Connection conn,String sql,Object[] params,ResultSetHandler rsh) The only difference between this method and the above method is the position of the parameter . But the variable parameter must be in the last item , So this method has expired .
2、query(String sql,ResultSetHandler rsh,Object[] params) Method
This method is used to perform query operations , Compared with the first method , It does not need to Connection Object passed to method , It can be from the data source provided to the constructor DataSource Or used setDataSource() Method .
3、query(Connection conn,String sql,ResultSetHandler rsh) Method
This method is used to execute a query result that does not require replacement parameters .
4、update(Connection conn,String sql,Object[] params) Method
This method is used to perform insertion 、 Update or delete , among , Parameters params Express SQL Substitution parameters in the statement .
5、update(Connection conn,String sql) Method
This method is used to perform insertion 、 Update or delete , It does not require substitution parameters .

ResultSetHandler Interface
ResultSetHandler The interface is used to handle ResultSet Result set , It can convert the data in the result set into different forms . Depending on the type of data in the result set ,ResultSetHandler Different implementation classes are provided .
1)AbstractKeyedHandler: This is an abstract class , It can convert the data in the result set into Map Storage .
2)AbstractListHandler: This is an abstract class , It can convert the data in the result set into List Storage .
3)ArrayHandler: Convert the first row of data in the result set to an object array .
4)ArrayListHandler: Turn each row of data in the result set into an object array , Then store the array in List in .
5)BaseResultSetHandler: An extension that converts the result set into other objects .
6)BeanHandler: Store the first row of data in the result set in a corresponding javaBean In the example .
7)BeanListHandler: Store each row of data in the result set in a corresponding javaBean In the example , then JavaBean The instance is stored in List in .
8)BeanMapHandler: Store each row of data in the result set in a corresponding javaBean In the example , Then according to the specified key Put each JavaBean Then store it in a Map in .
9)ColumnListHandler: Store the data of a column in the result set in List in
10)KeyedHandler: Encapsulate each row of data in the result set into a Map in , Then according to the specified key Put each JavaBean Then store it in a Map in .
11)MapHandler: Encapsulate the first row of data in the result set into a Map in ,key Is the column name ,value Is the corresponding value .
12)MapListHandler: Encapsulate each row of data in the result set into a Map in , Store it in List in .
13)ScalarHandler: Store the data in one column of a record in the result set as Object object .
in addition , stay ResultSetHandler Interface , Provides a separate method handle(java.sql.ResultSet rs), If the above implementation class does not provide the desired function , You can customize an implementation ResultSetHandler The class of the interface , And then by rewriting handle() Method , Realize the processing of result set .

3 rely on

        <dependency>
            <groupId>commons-dbutils</groupId>
            <artifactId>commons-dbutils</artifactId>
            <version>1.7</version>
        </dependency>
        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>7.3.0</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.49</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.2.10</version>
        </dependency>

Tools

public class Dbutils {

    private DruidDataSource dataSource;

    @BeforeMethod
    public void testBefore() throws IOException, ClassNotFoundException, SQLException {
        /*Properties pros=new Properties();
        //properties.load(ClassLoader.getSystemClassLoader().getResourceAsStream("/jdbc.properties"));
        pros.load(Dbutils.class.getResourceAsStream("/jdbc.properties"));
        String user = pros.getProperty("user");
        String password = pros.getProperty("password");
        String url = pros.getProperty("url");
        String driverClass = pros.getProperty("driverClass");
        Class.forName(driverClass);
        Connection con = DriverManager.getConnection(url,user,password)*/

        Properties properties=new Properties();
        properties.load(Dbutils.class.getResourceAsStream("/jdbc.properties"));
        dataSource = new DruidDataSource();
        dataSource.configFromPropety(properties);
    }

    @Test
    public void test() throws SQLException {
        DruidPooledConnection dpc =  dataSource.getConnection();
        PreparedStatement preparedStatement=dpc.prepareStatement("show tables");
        ResultSet resultSet=preparedStatement.executeQuery();
        while(resultSet.next()) {
            System.out.println(resultSet.getString(1));
        }
    }
}

The configuration file

druid.name=myDruid
druid.url=jdbc:mysql://localhost:3306/dc?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=GMT%2B8
druid.driverClassName=com.mysql.jdbc.Driver
druid.username=root
druid.password=root

4 DBUtils

DbUtils: Connect to database objects ----jdbc Collection class of auxiliary methods , Thread safety

4.1 Dbutils Introduction to three core functions

QueryRunner  Provided in pairs sql Statement operation API.
ResultSetHandler  Interface , Used for definition select After the operation , How to encapsulate result sets .
DbUtils  class , It's a tool class , Defines methods for closing resources and transactions 

4.2 QueryRunner

Jump to the directory
Provide data sources : Use the connection object of the passed data source

Construction method
QueryRunner(DataSource) : Create core classes , And provide data source , Internal maintenance Connection
Common method

1 update(String sql , Object ... params):  perform DML sentence   Used to execute addition, deletion and modification statements 
2 query(String sql , ResultSetHandler , Object ... params) :  perform DQL sentence , And encapsulate the query results into objects . Used to execute query statements 
 No data source is provided :  You need to provide your own connection objects 
3.batch(): Used to perform batch processing 

Construction method
QueryRunner() : Create core classes , No data source provided , When carrying out specific operations , It needs to be provided manually Connection
Common method
update(Connection conn , String sql , Object … params) : Use the Connection, complete
DML sentence
query(Connection conn , String sql , ResultSetHandler , Object … params) : Use the Connection, perform DQL sentence , And encapsulate the query results into objects .
QueryRunner Implementation add 、 to update 、 Delete operation
Jump to the directory

update(String sql, Object… params) : Used to add table data 、 Delete 、 update operation
queryRunner.update(sql): For increasing 、 Delete 、 modify
queryRunner.query(sql,rsh): For queries

 @Test
    public void insert() throws Exception {
        //  Get a to execute SQL Statement object 
        QueryRunner qr = new QueryRunner(dataSource);
        String sql = "INSERT INTO stu(name, score) VALUES(?, ?)";
        Object[] params = {" Centenary mountain ", "50"};
        int count = qr.update(sql, params);
        System.out.println(" Successful implementation :=" + count);
    }
    
@Test
 public static void insert(){
        QueryRunner qr = new QueryRunner();
        String sql = "insert into student values(112,' Zhang San ',19)";
        Connection conn = null;
        try {
            conn = JDBCUtils.getConnection();
            int count = qr.update(conn,sql);
            System.out.println(count);
            DbUtils.closeQuietly(conn);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void update() throws Exception {
        QueryRunner qr = new QueryRunner(dataSource);
        String sql = "UPDATE stu SET name=?,score=? WHERE id=?";
        Object[] params = {" Mango. 99", "99", 6};
        int count = qr.update(sql, params);
        System.out.println(count);
    }

@Test
   public static void update(){
        QueryRunner qr = new QueryRunner();
        String sql = "update student set sage= sage+10 where sno = 110";
        Connection conn = null;
        try {
            conn = JDBCUtils.getConnection();
            int count = qr.update(conn,sql);
            System.out.println(count);
            DbUtils.closeQuietly(conn);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
、
   @Test
    public void delete() throws SQLException {
        QueryRunner queryRunner = new QueryRunner(dataSource);
        String sql = "DELETE from stu WHERE id = ?";
        Object[] params = {6};
        int r = queryRunner.update(sql, params);
        System.out.println(r);
    }
@Test
  public static void delete(){
        QueryRunner qr = new QueryRunner();
        String sql = "delete from student where sno = 112";
        Connection conn = null;
        try {
            conn = JDBCUtils.getConnection();
            int count = qr.update(conn,sql);
            System.out.println(count);
            DbUtils.closeQuietly(conn);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

QueryRunner Implement query operation
Jump to the directory

query(String sql, ResultSetHandler rsh, Object… params) Used to complete the query operation of table data
Parameters :
String sql: sql sentence , Parameter use ? replace
ResultSetHandler<T> rsh: Result set processor , Interface , The implementation class object must be passed
Object … params: Variable parameters , Pass parameter list , Array .
effect : to sql in ? Assign a value .
ResultSetHandler Result set
Jump to the directory

BeanHandler: Encapsulates the first record in the result set into a specified JavaBean in .
BeanListHandler: Encapsulate each record in the result set to the specified JavaBean in , Will these JavaBean After packaging to List Collection
ScalarHandler: It is used for single data . for example select count(*) from Table operations .
ColumnListHandler: Set the value of the specified column in the result set , Package into a List Collection
JavaBean
Jump to the directory
JavaBean It's a class , It is often used to encapsulate data in development ,. Has the following characteristics .

Need to implement interface :java.io.Serializable , Usually, the step of implementing the interface is omitted , Will not affect the program .
Provide private fields :private type Field name ;
Provide getter/setter Method :
Provide nonparametric construction
BeanHandler
Jump to the directory

One of the ways to process the result set of query data table :
BeanHandler Processing mode The data in the first row of the result set of the data table , Encapsulated into JavaBean Class object
Construction method : BeanHandler(Class<T> type) Pass a Class Type object , The object of which class the result is encapsulated

 @Test
    public void testQueryBeanHandler() throws Exception{
        QueryRunner queryRunner = new QueryRunner(dataSource);
        String sql = "SELECT * FROM stu WHERE id = ?";
        Object[] params = {5};
        //  Query and encapsulate 
        Stu pro = queryRunner.query(sql, new BeanHandler<>(Stu.class), params);
        System.out.println(pro);
    }

BeanListHandler
Jump to the directory

One of the ways to process the result set of query data table :
BeanListHandler Processing mode The data in each row of the data table , Encapsulated into JavaBean Class object , Multiple lines of data , Multiple JavaBean object , Storage List aggregate .

   @Test
   public void testQueryBeanListHandler() throws Exception{
       QueryRunner queryRunner = new QueryRunner(DBCPUtil.getDataSource());
       String sql = "SELECT * FROM product";
       Object[] params = {};
       List<Product> pros = queryRunner.query(sql, new BeanListHandler<Product>(Product.class), params);
       for (Product pro : pros) {
           System.out.println(pro);
       }
   }

ScalarHander
Jump to the directory

effect : Put a column of the query results , Store in List A collection of objects
Construction method :
public ScalarHandler(): Get the first column of the first row of the query result
public ScalarHandler(int index): Get the first row of query results index Column
public ScalarHandler(String ColumnName): Get the first row of the query result ColumnName Column

    @Test
    public void testQueryScalarHandler() throws Exception{
        QueryRunner queryRunner = new QueryRunner(DruidUtil.getDataSource());
        String sql = "SELECT * FROM product WHERE pid = ?";
        Object[] params = {2};
        //  Represents the second column of the second row of the query 
        Object o = queryRunner.query(sql, new ScalarHandler(2), params);
        System.out.println(o);
    }

ColumnListHandler
Jump to the directory

Get the value of a column in the database , Usually used to summarize ; Commonly used in Aggregate functions

effect : Put a column of the query results , Store in List A collection of objects . be used for Aggregate functions
Construction method :
public ColumnListHandler(): Store the contents of the first column in List Collection
public ColumnListHandler(int index): Store the contents of the specified number column in List Collection
public ColumnListHandler(String ColumnName): Store the contents of the column corresponding to the specified column name in List Collection

    @Test
    public void testQueryColumnListHandler() throws Exception{
        QueryRunner queryRunner = new QueryRunner(C3P0Util.getDataSource());
        String sql = "SELECT * FROM product";
        // List<Object> list = queryRunner.query(sql, new ColumnListHandler());//  The default query is the first column 
        // List<Object> list = queryRunner.query(sql, new ColumnListHandler(2)); //  Query the second column specified by the relation table 
        List<Object> list = queryRunner.query(sql, new ColumnListHandler("pname"));
        for (Object o : list) {
            System.out.println(o);
        }
    }

2.ResultSetHandler Interface
1.ArrayHandler: The first row of data in the query result , Save to Object Array

    public static void arrayHandler(){
        QueryRunner qr = new QueryRunner();
        String sql = "select * from student";

        try {
            Connection conn = JDBCUtils.getConnection();
            Object[] query = qr.query(conn, sql, new ArrayHandler());
            for(Object obj : query)
                System.out.print(obj);
            DbUtils.closeQuietly(conn);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

2.arrayListHandler: The result of the query , Each line is first wrapped in Object Array , Then store the data in List aggregate

    public static void arrayListHandler(){
        QueryRunner qr = new QueryRunner();
        String sql = "select * from student";
        try {
            Connection conn = JDBCUtils.getConnection();
            List<Object[]> query = qr.query(conn, sql, new ArrayListHandler());
            for(Object[] objs : query){
                for (Object obj : objs){
                    System.out.print(obj+"  ");
                }
                System.out.println();
                DbUtils.closeQuietly(conn);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

3.BeanHandler: The first row of data in the query result , Package to student object

    public static void BeanHandler(){
        QueryRunner qr = new QueryRunner();
        String sql = "select * from student";
        try {
            Connection conn = JDBCUtils.getConnection();
            Student query = qr.query(conn, sql, new BeanHandler<Student>(Student.class));
            System.out.println(query);
            DbUtils.closeQuietly(conn);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

4.BeanLIstHandler: Encapsulate each row of the query result into student object , And then deposit List aggregate

    public static void BeanListHandler(){
        QueryRunner qr = new QueryRunner();
        String sql = "select * from student";
        try {
            Connection conn = JDBCUtils.getConnection();
            List<Student> query = qr.query(conn, sql, new BeanListHandler<Student>(Student.class));
            for (Student student : query){
                System.out.println(student+"  ");
            }
            DbUtils.closeQuietly(conn);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

5.ColumnListHandler: Encapsulate the data of the specified column of the query result into List Collection

    public static void ColumnListHandler(){
        QueryRunner qr = new QueryRunner();
        String sql = "select * from student";
        try {
            Connection conn = JDBCUtils.getConnection();
            List<Object> sno = qr.query(conn, sql, new ColumnListHandler<>("sno"));
            for (Object obj : sno)
                System.out.println(obj);
            DbUtils.closeQuietly(conn);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

6.ScalarHanlder: Put a column in the first row of the result set into an object

    public static void ScalarHandler(){
        QueryRunner qr = new QueryRunner();
        String sql = "select count(*) from student";
        try {
            Connection conn = JDBCUtils.getConnection();
            long query = qr.query(conn, sql, new ScalarHandler<Long>());
            System.out.println(query);
            DbUtils.closeQuietly(conn);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

7.MapHandler: Encapsulate the first row of data in the result set into a Map

    public static void MapHandler(){
        QueryRunner qr = new QueryRunner();
        String sql = "select * from student where sno = ?";
        try {
            Connection conn = JDBCUtils.getConnection();
            Map<String, Object> query = qr.query(conn, sql, new MapHandler(), 110);
            System.out.println(query);
            DbUtils.closeQuietly(conn);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

8.MapListHandler: Encapsulate each row of data in the result set into a Map in , Then store it in List

    public static void MapListHandler() {
        QueryRunner qr = new QueryRunner();
        String sql = "select * from student where sno = ?";
        try {
            Connection conn = JDBCUtils.getConnection();
            List<Map<String, Object>> query = qr.query(conn, sql, new MapListHandler(),110);
            for (Map<String, Object> map : query) {
                System.out.println(map);
            }
            DbUtils.closeQuietly(conn);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

KeyedHandler: Encapsulate each row of data in the result set into a Map in (List), And then put these map Save one more map
public static void KeyedHandler(){
QueryRunner queryRunner = new QueryRunner();
String sql = “select * from student”;
Map<String,Map<String,Object>>map = null;
try {
Connection conn = JDBCUtils.getConnection();
map = queryRunner.query(conn,sql,new KeyedHandler(“sname”));
for(Map.Entry<String,Map<String,Object>> entry : map.entrySet()){
System.out.println(entry.getKey());
System.out.println(entry.getValue());
}
DbUtils.closeQuietly(conn);
} catch (SQLException e) {
e.printStackTrace();
}
}

DBUtils class
It provides information about closing resources and transactions rollback,commit operation . The methods inside are static .

5 Summary

Jump to the directory
DBUtils Tools

effect : simplify JDBC The operation of
DBUtils Common classes and methods

QueryRunner Used to perform SQL Statement object

update(Connection conn, String sql, Object… params) Insert table record 、 Update table records 、 Delete table record
query(Connection conn, String sql, ResultSetHandler handler, Object… params) Query table record
ResultSetHandler The object that handles the result set

BeanHandler: Encapsulates the first record in the result set into a specified javaBean in .
BeanListHandler: Encapsulate each record in the result set to the specified javaBean in , Will these javaBean After packaging to List Collection
ScalarHandler: It is used for single data . for example select count(*) from Table operations .
ColumnListHandler: Sets the field value of the specified column in the result set to , Package into a List Collection

public class Dbutils {

    private static DruidDataSource dataSource;

    @BeforeMethod
    public void testBefore() throws IOException, ClassNotFoundException, SQLException {
        Properties properties=new Properties();
        properties.load(Dbutils.class.getResourceAsStream("/jdbc.properties"));
        dataSource = new DruidDataSource();
        dataSource.configFromPropety(properties);
    }

    @AllArgsConstructor
    private static class InitRunnable implements Runnable {
        private CountDownLatch countDownLatch;
        @SneakyThrows
        @Override
        public void run() {
            System.out.println(new Date());
            Dbutils.insert();
            countDownLatch.countDown();
        }
    }

    @Test
    public void curent() throws InterruptedException {
        CountDownLatch countDownLatch=new CountDownLatch(1000);
        List<Thread> workers = Stream
                .generate(() -> new Thread(new InitRunnable(countDownLatch)))
                .limit(1000)
                .collect(toList());
        workers.forEach(Thread::start);
        countDownLatch.await();
    }

    public static void insert() throws Exception {
        //  Get a to execute SQL Statement object 
        QueryRunner qr = new QueryRunner(dataSource);
        String sql = "INSERT INTO stu(name, score) VALUES(?, ?)";
        Object[] params = {" Centenary mountain ", "50"};
        int count = qr.update(sql, params);
    }
}
原网站

版权声明
本文为[qq_ thirty-seven million seven hundred and five thousand five h]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/160/202206090552496722.html