首页 > 其他分享 >DBUtils工具类实现增删改查

DBUtils工具类实现增删改查

时间:2023-09-10 17:07:32浏览次数:41  
标签:java 改查 commons apache org 增删 import DBUtils conn



DBUtils工具类实现增删改查

  • 一、数据库连接池Druid工具类
  • 二、DBUtils实现增删改
  • 三、DBUtils实现查询单条数据
  • 四、DBUtils实现查询批量数据
  • 五、DBUtils实现按键值对查询数据
  • 六、查询单个数据


  • QueryRunner提供对sql语句操作的API
  • ResultSetHandler接口,用于定义select操作后,怎样封装结果集

结果集处理类

描述

ArrayHandler

将结果集中的第一条记录封装到一个Object[]数组中,数组中的每一个元素就是这条记录中的每一个字段的值

ArrayListHandler

将结果集中的每一条记录都封装到一个Object[]数组中,将这些数组在封装到List集合中

BeanHandler

将结果集中第一条记录封装到一个制定的javaBean中

BeanListHandler

将结果集中每一条记录封装到指定的javaBean中,将这些javaBean在封装到List集合中

ColumnListHandler

将结果集中指定的列的字段值,封装到一个List集合中

KeyedHandler

将结果集中每一条记录封装到Map<String,Object>,在将这个map集合做为另一个Map的value,另一个Map集合的key是指定的字段的值

MapHandler

将结果集中第一条记录封装到了Map<String,Object>集合中,key就是字段名称,value就是字段值

MapListHandler

将结果集中每一条记录封装到了Map<String,Object>集合中,key就是字段名称,value就是字段值,在将这些Map封装到List集合中

ScalarHandler

它是用于单个数据。例如select count(*) from 表操作

一、数据库连接池Druid工具类

import com.alibaba.druid.pool.DruidDataSourceFactory;
import org.apache.commons.beanutils.PropertyUtils;

import javax.sql.DataSource;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

public class JdbcUtils {
    private static DataSource ds = null;

    static {
        try {
            Properties props = new Properties();
            props.load(JdbcUtils.class.getClassLoader().getResourceAsStream("druid.properties"));
            ds = DruidDataSourceFactory.createDataSource(props);
        } catch (Exception e) {
                throw new RuntimeException("读取配置文件异常", e);
        }
    }

    //Druid连接池
    public static Connection getDruidConnection() throws Exception {
        Connection conn = null;
        conn = ds.getConnection();
        return conn;
    }


    public static void release(Connection conn) throws SQLException {
        if(conn != null) conn.close();
    }


    public static void release(Connection conn, PreparedStatement ps) throws SQLException {
        if(ps!=null) ps.close();
        if(conn!=null) conn.close();
    }

    public static void release(Connection conn, PreparedStatement ps, java.sql.ResultSet rs) throws SQLException {
        if(rs!=null) rs.close();
        if(ps!=null) ps.close();
        if(conn!=null) conn.close();
    }
}

二、DBUtils实现增删改

import com.bigdata.plus.Entity.DatabaseInfo;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import org.junit.Test;

import java.sql.Connection;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class DBUtilsTest {


    private QueryRunner qr = new QueryRunner();

    @Test
    public void test1() throws Exception {
        Connection conn = JdbcUtils.getDruidConnection();
        String sql = "insert into dw.stuinfo(stunum,name,age,hobby,create_time) values(?,?,?,?,?)";
        Object[] params = {10012, "杀生丸", 18, "打妖怪",new java.sql.Date(new Date().getTime())};
        int row = qr.update(conn, sql, params);

        System.out.println("已影响" + row + "行");

        JdbcUtils.release(conn,null,null);
    }
}

成功插入数据:

DBUtils工具类实现增删改查_apache

三、DBUtils实现查询单条数据

import com.bigdata.plus.Entity.DatabaseInfo;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import org.junit.Test;

import java.sql.Connection;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class DBUtilsTest {


    private QueryRunner qr = new QueryRunner();

  
    @Test
    public void test2() throws Exception {
        Connection conn = JdbcUtils.getDruidConnection();
        String sql = "select t.TABLE_SCHEMA as databaseName,CONCAT_WS('.',t.TABLE_SCHEMA,t" +
                ".TABLE_NAME)" +
                " as " +
                "tableName,t.TABLE_COMMENT as tableComment,t.TABLE_ROWS as tableRows,k.COLUMN_NAME as " +
                "tableKey\n" +
                "from INFORMATION_SCHEMA.TABLES as t\n" +
                "inner join INFORMATION_SCHEMA.KEY_COLUMN_USAGE as k\n" +
                "on k.TABLE_NAME=t.TABLE_NAME and CONSTRAINT_NAME = 'PRIMARY' and t.TABLE_SCHEMA=?";
        Object[] params = {"dw"};
        BeanHandler<DatabaseInfo> rsh = new BeanHandler<>(DatabaseInfo.class);
        DatabaseInfo databaseInfo = qr.query(conn, sql, rsh, params);

        System.out.println(databaseInfo);

        JdbcUtils.release(conn,null,null);
    }
}

DBUtils工具类实现增删改查_java_02

四、DBUtils实现查询批量数据

package com.bigdata.plus;

import com.bigdata.plus.Entity.DatabaseInfo;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import org.junit.Test;

import java.sql.Connection;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class DBUtilsTest {


    private QueryRunner qr = new QueryRunner();

    @Test
    public void test3() throws Exception {
        Connection conn = JdbcUtils.getDruidConnection();
        String sql = "select t.TABLE_SCHEMA as databaseName,CONCAT_WS('.',t.TABLE_SCHEMA,t" +
                ".TABLE_NAME)" +
                " as " +
                "tableName,t.TABLE_COMMENT as tableComment,t.TABLE_ROWS as tableRows,k.COLUMN_NAME as " +
                "tableKey\n" +
                "from INFORMATION_SCHEMA.TABLES as t\n" +
                "inner join INFORMATION_SCHEMA.KEY_COLUMN_USAGE as k\n" +
                "on k.TABLE_NAME=t.TABLE_NAME and CONSTRAINT_NAME = 'PRIMARY' and t.TABLE_SCHEMA=?";
        Object[] params = {"dw"};
        BeanListHandler<DatabaseInfo> rsh = new BeanListHandler<>(DatabaseInfo.class);
        List<DatabaseInfo> databaseInfos = qr.query(conn, sql, rsh, params);

        for(DatabaseInfo databaseInfo : databaseInfos ){
            System.out.println(databaseInfo);
        }

        JdbcUtils.release(conn,null,null);
    }
}

DBUtils工具类实现增删改查_DBUtils工具类_03

五、DBUtils实现按键值对查询数据

import com.bigdata.plus.Entity.DatabaseInfo;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import org.junit.Test;

import java.sql.Connection;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class DBUtilsTest {


    private QueryRunner qr = new QueryRunner();

    @Test
    public void test4() throws Exception {
        Connection conn = JdbcUtils.getDruidConnection();
        String sql = "select t.TABLE_SCHEMA as databaseName,CONCAT_WS('.',t.TABLE_SCHEMA,t" +
                ".TABLE_NAME)" +
                " as " +
                "tableName,t.TABLE_COMMENT as tableComment,t.TABLE_ROWS as tableRows,k.COLUMN_NAME as " +
                "tableKey\n" +
                "from INFORMATION_SCHEMA.TABLES as t\n" +
                "inner join INFORMATION_SCHEMA.KEY_COLUMN_USAGE as k\n" +
                "on k.TABLE_NAME=t.TABLE_NAME and CONSTRAINT_NAME = 'PRIMARY' and t.TABLE_SCHEMA=?";
        Object[] params = {"dw"};
        MapListHandler mapListHandler = new MapListHandler();
        List<Map<String, Object>> query = qr.query(conn, sql, mapListHandler, params);

        for(Map<String,Object> map : query){
            Set<Map.Entry<String, Object>> entries = map.entrySet();

            for(Map.Entry<String,Object> entry : entries){
                String key = entry.getKey();
                Object value = entry.getValue();

                System.out.println(key + " ======== " + value);
            }

            System.out.println("-----------------------------------");

        }

        JdbcUtils.release(conn,null,null);
    }

}

DBUtils工具类实现增删改查_DBUtils工具类_04

六、查询单个数据

import com.bigdata.plus.Entity.DatabaseInfo;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import org.junit.Test;

import java.sql.Connection;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class DBUtilsTest {

    private QueryRunner qr = new QueryRunner();

    @Test
    public void test5() throws Exception {
        Connection conn = JdbcUtils.getDruidConnection();
        String sql = "select count(1) from dw.stuinfo";
        ScalarHandler<Object> objectScalarHandler = new ScalarHandler<>();
        Object query = qr.query(conn, sql, objectScalarHandler);

        System.out.println(query);

        JdbcUtils.release(conn,null,null);
    }

}

DBUtils工具类实现增删改查_apache_05


标签:java,改查,commons,apache,org,增删,import,DBUtils,conn
From: https://blog.51cto.com/u_12080573/7426640

相关文章

  • 使用IDEA连接Hive数据库使用Java代码实现增删改查还需要一个Hive配置类
    可以取名为:HiveConfig--packagecom.example.config;importcom.alibaba.druid.pool.DruidDataSource;importlombok.Data;importorg.springframework.beans.factory.annotation.Qualifier;importorg.springframework.boot.context.properties.ConfigurationProperties;i......
  • ElasticSearch的常规增删改查操作
    一、Restful简介RESTFul:RepresentationalStateTransfer,中文意思:表现层状态转化。变现层指的是资源的表现层,这里的资源是指网络上的信息,比如一张图片,一段文本,一步电影,那么每个资源在网络上都有一个标识,可以理解为一个ID,每个资源都有一个ID去表示它,这个ID就称之为URL。当我们给了......
  • MySQL增删改查的基本命令
    1.数据库相关命令1.查看所有的数据库showdatabases;2.查看一个库的基本信息showcreatedatabasedb1;3.创建一个数据库createdatabasedb1;4.删除一个数据库dropdatabasedb1;5.修改库的字符编码alterdatabasecharset='utf8';2.表相关命令1.创建......
  • 如何在Java中连接MySQL数据库并实现增删改查操作
    要在Java中连接MySQL数据库并实现增删改查操作,你需要遵循以下步骤:导入所需的Java库:你需要导入Java中与MySQL连接和操作相关的库。常用的库包括JDBC(JavaDatabaseConnectivity)和MySQL驱动程序。importjava.sql.*;建立数据库连接:使用JDBC连接MySQL数据库,你需要提供数据库的URL、用......
  • 20230829-sessionStorage实现数据的增删改查
    sessionStorage实现数据的增删改查#sessionStorage实现数据的增删改查(sessionStorage的方法对比localstorage)<!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"><metaname="viewport"content="width=......
  • 220230825-localstorage实现数据的增删改查
    演示案例<!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"><metaname="viewport"content="width=device-width,initial-scale=1.0"><title>Document</title>......
  • C#访问SQLite完整增删改查代码
    文章转载自:https://wobushixiaohai.blog.csdn.net/article/details/117804179?spm=1001.2101.3001.6650.3&utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7ERate-3-117804179-blog-103633083.235%5Ev38%5Epc_relevant_anti_vip_base&depth_1-u......
  • localstorage实现数据的增删改查
    演示案例<!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"><metaname="viewport"content="width=device-width,initial-scale=1.0"><title>Document</title>......
  • python字典的应用一(增删改查)
    #一.有如下字典内容用程序解答下面的题目dic={'python':95,'java':99,'c':100}#1.字典的长度是多少print(len(dic))#2.请修改'java'这个key对应的value值为98dic["java"]=98print(dic)#3.删除c这个keydeldic["c"]print(di......
  • 6-6 Oracle表复杂查询 -合并查询-增删改数据
    Oracle基础知识整理:C站下载链接1Oracle基础知识2Oracle安装(附详细安装操作手册)3Oracle基本使用4Oracle用户管理6-1Oracle表的管理-创建修改表6-2Oracle表的管理-表查询6-3Oracle表的管理-表复杂查询6-4Oracle表复杂查询-多表查询6-5Oracle表复杂查询-子查询文章......