Apache Commons DbUtils 使用

介绍

Apache Commons DbUtils
The Apache Commons DbUtils package is a set of Java utility classes for easing JDBC development.

<!-- https://mvnrepository.com/artifact/commons-dbutils/commons-dbutils -->
<dependency>
    <groupId>commons-dbutils</groupId>
    <artifactId>commons-dbutils</artifactId>
    <version>1.6</version>
</dependency>

简单使用


package mybatis.cn.db;

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

/**
 * @Author yanyg
 * @Date 2020/6/22 9:01
 * @Descripetion admin
 */
public class DbUtil {
    private static String url = "jdbc:mysql://127.0.0.1:3306/nabs_base?useUnicode=true&characterEncoding=utf8mb4&useSSL=false";
    private static String username = "root";
    private static String password = "root";

    public static Connection getConnection() {
        Connection conn = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        try {
            conn = DriverManager.getConnection(url, username, password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }
}

@RunWith(SpringRunner.class)
@SpringBootTest
public class DBUtilsTest {

    @Test
    public  void testQuery() {
        //创建连接
        Connection conn = DbUtil.getConnection();
        //创建SQL执行工具
        QueryRunner queryRunner = new QueryRunner();
        List<IdValidLogSum> list = null;
        try {
            //执行SQL查询,并获取结果
            list = queryRunner.query(conn, "select * from person", new BeanListHandler<>(IdValidLogSum.class));
        } catch (SQLException e) {
            e.printStackTrace();
        }
        if (list != null) {
            //输出查询结果
            list.forEach(System.out::println);
        }
        //关闭数据库连接
        DbUtils.closeQuietly(conn);
    }

}

你可能感兴趣的:(常用工具类)