JDBC增删改查示例

news2025/7/19 16:52:19

数据库表

CREATE TABLE `customers` (
  `id` int NOT NULL AUTO_INCREMENT,
  `name` varchar(15) DEFAULT NULL,
  `email` varchar(20) DEFAULT NULL,
  `birth` date DEFAULT NULL,
  `photo` mediumblob,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=39 DEFAULT CHARSET=gb2312;

引入的依赖   下图是为了快速将inputStream转byte[]引入的一个依赖

没有使用连接池

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.30</version>
</dependency>
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.13.2</version>
    <scope>test</scope>
</dependency>

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.11.0</version> <!-- 使用最新版本 -->
</dependency>

封装的工具类,这个工具类如果说想使用泛型  需要把除了closed和getConnection的其他几个方法的静态去掉

package com.utils;

import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;

/**
 * @author hrui
 * @date 2023/10/16 8:45
 */
//public  class DBUtils2<T> {
public  class DBUtils2 {
    private static ResourceBundle bundle=ResourceBundle.getBundle("jdbc");
    private static String driver=bundle.getString("jdbc.driver");
    private static String url=bundle.getString("jdbc.url");
    private static String username=bundle.getString("jdbc.username");
    private static String password=bundle.getString("jdbc.password");

    static{
        try {
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

//    private Class<T> clazz;
//
//    {
//        //获取这个类带泛型的父类DBUtils2<某个类>
//        Type genericSuperclass = this.getClass().getGenericSuperclass();
//        ParameterizedType parameterizedType=(ParameterizedType)genericSuperclass;
//        //获取父类泛型
//        Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
//        clazz=(Class<T>)actualTypeArguments[0];
//    }


    //通用查询多个  添加事务后conn由外部传入,在关闭时候也由外部关闭,不再次方法关闭conn
    public static <T> List<T> selectList(Connection conn,Class<T> clazz, String sql, Object...args){
        PreparedStatement ps=null;
        ResultSet rs=null;

        try {
            ps=conn.prepareStatement(sql);

            for(int i=0;i<args.length;i++){
                ps.setObject(i+1, args[i]);
            }
            rs = ps.executeQuery();
            ResultSetMetaData metaData = rs.getMetaData();
            int columnCount = metaData.getColumnCount();
            List<T> list=new ArrayList<>();
            while(rs.next()){
                T t = clazz.newInstance();
                for(int i=0;i<columnCount;i++){
                    Object object = rs.getObject(i + 1);
                    //String columnName = metaData.getColumnName(i + 1); 这个方法返回实际列名
                    String columnLabel = metaData.getColumnLabel(i + 1);//该方法返回别名,没有别名就返回列名
                    columnLabel = getString(columnLabel);
                    Field field = clazz.getDeclaredField(columnLabel);
                    field.setAccessible(true);
                    field.set(t,object);
                }
                list.add(t);
            }
            return list;
        } catch (Exception e) {
            e.printStackTrace();

        }finally {
            DBUtils.closed(null,ps,rs);
        }
        return null;
    }

    private static String getString(String columnLabel) {
        if (columnLabel.contains("_")) {
            StringBuilder result = new StringBuilder();
            boolean convertNextCharToUpperCase = false;
            for (char c : columnLabel.toCharArray()) {
                if (c == '_') {
                    convertNextCharToUpperCase = true;
                } else {
                    if (convertNextCharToUpperCase) {
                        result.append(Character.toUpperCase(c));
                        convertNextCharToUpperCase = false;
                    } else {
                        result.append(c);
                    }
                }
            }
        }
        return columnLabel;
    }

    //通用查询单个  添加事务后conn由外部传入,在关闭时候也由外部关闭,不再次方法关闭conn
    public static <T> T selectOne(Connection conn,Class<T> clazz,String sql,Object...args){

        PreparedStatement ps=null;
        ResultSet rs=null;

        try {

            ps=conn.prepareStatement(sql);

            for(int i=0;i<args.length;i++){
                ps.setObject(i+1, args[i]);
            }
            rs = ps.executeQuery();
            ResultSetMetaData metaData = rs.getMetaData();
            int columnCount = metaData.getColumnCount();
            if(rs.next()){
                T t = clazz.newInstance();
                for(int i=0;i<columnCount;i++){
                    Object object = rs.getObject(i + 1);
                    //System.out.println(object.getClass());
                    String columnLabel = metaData.getColumnLabel(i + 1);
                    columnLabel = getString(columnLabel);
                    Field field = clazz.getDeclaredField(columnLabel);
                    field.setAccessible(true);
                    field.set(t,object);
                }
                return t;
            }
        } catch (Exception e) {
            e.printStackTrace();

        }finally {
            DBUtils.closed(null,ps,rs);
        }
        return null;
    }




    public static Connection getConnection() throws SQLException {
        Connection connection = DriverManager.getConnection(url, username, password);
        return connection;
    }
    //通用增删改方法  添加事务后conn由外部传入,在关闭时候也由外部关闭,不再次方法关闭conn
    public static int update(Connection conn,String sql,Object...args){
        PreparedStatement ps=null;
        int count=0;
        try {
            ps = conn.prepareStatement(sql);
            for(int i=0;i<args.length;i++){
                ps.setObject(i+1, args[i]);
            }
            count = ps.executeUpdate();
            //ps.execute();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DBUtils.closed(null,ps,null);
        }

        return count;
    }

    //一些特殊查询封装的方法,例如select count(*) from xxx
    public static <E> E getValue(Connection conn,String sql,Object...args){
        PreparedStatement ps=null;
        ResultSet rs=null;
        try {
            ps = conn.prepareStatement(sql);
            for(int i=0;i<args.length;i++){
                ps.setObject(i+1, args[i]);
            }
            rs=ps.executeQuery();
            if(rs.next()){
                return (E)rs.getObject(1);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DBUtils2.closed(null,ps,rs );
        }
        return null;
    }


    public static void closed(Connection conn, Statement st, ResultSet rs){
        if(rs!=null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(st!=null){
            try {
                st.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(conn!=null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

接口

public interface CustomerDao {
    int insertCustomer(Connection conn, Customers cust);

    int deleteCustomerById(Connection conn,Integer id);

    int updateCustomer(Connection conn,Customers cust);

    Customers selectCustomerById(Connection conn,Integer id);

    List<Customers> selectAllCustomers(Connection conn);

    //查询表中由多少条数据 count(*)返回Long
    Long getCount(Connection conn);

    Date getMaxBirth(Connection conn);
}

接口实现类

public class CustomerDaoImpl extends DBUtils2 implements CustomerDao{
    @Override
    public int insertCustomer(Connection conn, Customers cust) {
        String sql="insert into customers(name,email,birth,photo)value(?,?,?,?)";
        int count = update(conn, sql, cust.getName(), cust.getEmail(), cust.getBirth(), cust.getPhoto());
        return count;
    }

    @Override
    public int deleteCustomerById(Connection conn, Integer id) {
        String sql="delete from customers where id=?";
        int count = update(conn, sql, id);
        return count;
    }

    @Override
    public int updateCustomer(Connection conn, Customers cust) {
        String sql="update customers set name=?,email=?,birth=?,photo=? where id=?";
        int count = update(conn, sql, cust.getName(), cust.getEmail(), cust.getBirth(), cust.getPhoto(),cust.getId());
        return count;
    }

    @Override
    public Customers selectCustomerById(Connection conn, Integer id) {
        String sql="select * from customers where id=?";
        Customers customers = selectOne(conn, Customers.class, sql, id);
        return customers;
    }

    @Override
    public List<Customers> selectAllCustomers(Connection conn) {
        String sql="select * from customers";
        List<Customers> list = selectList(conn, Customers.class, sql);
        return list;
    }

    @Override
    public Long getCount(Connection conn) {
        String sql="select count(*) from customers";
        return getValue(conn, sql);
    }

    @Override
    public Date getMaxBirth(Connection conn) {
        String sql="select max(birth) from customers";
        return getValue(conn, sql);
    }
}

测试类

package com.utils;

import org.apache.commons.io.IOUtils;
import org.junit.jupiter.api.Test;


import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;

/**
 * @author hrui
 * @date 2023/10/16 16:00
 */
public class CustomterDaoImplTest {

    private CustomerDao customerDao=new CustomerDaoImpl();

    @Test
    public void insertCustomerTest(){
        Connection conn=null;
        try {
            conn = DBUtils2.getConnection();
            InputStream inputStream = CustomterDaoImplTest.class.getClassLoader().getResourceAsStream("123.jpg");
            byte[] imageBytes = IOUtils.toByteArray(inputStream);//这个需要引入commons-io
            // 关闭输入流
            inputStream.close();

            Customers cust=new Customers(null,"小白","xiaobai@163.com",new Date(),imageBytes);
            int i = customerDao.insertCustomer(conn, cust);
            System.out.println(i==1?"新增成功":"新增失败");
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            DBUtils2.closed(conn,null,null);
        }
    }
    @Test
    public void deleteCustomerByIdTest(){
        Connection conn=null;
        try {
            conn = DBUtils2.getConnection();
            int i = customerDao.deleteCustomerById(conn, 1);
            System.out.println(i==1?"删除成功":"删除失败");
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            DBUtils2.closed(conn,null,null);
        }
    };
    @Test
    public void updateCustomer(){
        Connection conn=null;
        try {
            conn = DBUtils2.getConnection();
            InputStream inputStream = CustomterDaoImplTest.class.getClassLoader().getResourceAsStream("123.jpg");
            byte[] imageBytes = IOUtils.toByteArray(inputStream);//这个需要引入commons-io
            // 关闭输入流
            inputStream.close();
            Customers cust=new Customers(2,"王菲菲","feifei@666.com",new Date(),imageBytes);

            int i = customerDao.updateCustomer(conn,cust);
            System.out.println(i==1?"更新成功":"更新失败");
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            DBUtils2.closed(conn,null,null);
        }
    };
    @Test
    public void selectCustomerById(){
        Connection conn=null;
        try {
            conn = DBUtils2.getConnection();
            Customers customers = customerDao.selectCustomerById(conn, 2);
            System.out.println(customers);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            DBUtils2.closed(conn,null,null);
        }
    };
    @Test
    public void selectAllCustomersTest(){
        Connection conn=null;
        try {
            conn = DBUtils2.getConnection();
            List<Customers> customers = customerDao.selectAllCustomers(conn);
            System.out.println(customers);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            DBUtils2.closed(conn,null,null);
        }
    };
    @Test
    //查询表中由多少条数据 count(*)返回Long
    public void getCount(){
        Connection conn=null;
        try {
            conn = DBUtils2.getConnection();
            Long count = customerDao.getCount(conn);
            System.out.println(count);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            DBUtils2.closed(conn,null,null);
        }
    };
    @Test
    public void getMaxBirth(){
        Connection conn=null;
        try {
            conn = DBUtils2.getConnection();
            Date maxBirth = customerDao.getMaxBirth(conn);
            System.out.println(maxBirth);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            DBUtils2.closed(conn,null,null);
        }
    };
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1102560.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Redis 面试必备 全知识点思维导图

脑图下载地址&#xff1a;https://mm.edrawsoft.cn/mobile-share/index.html?uuidcf5bf135744412-src&share_type1 事务 定义 事务是一个单独的隔离操作,事务中的所有操作都将序列化,有顺序的执行,事务执行的过程中不会被其他客服端发来的命令打断 作用 串联多个命令防…

【兔子王赠书第2期】《案例学Python(基础篇)》

文章目录 前言推荐图书本书特色本书目录本书样章本书读者对象粉丝福利丨评论免费赠书尾声 前言 随着人工智能和大数据的蓬勃发展&#xff0c;Python将会得到越来越多开发者的喜爱和应用。身边有很多朋友都开始使用Python语言进行开发。正是因为Python是一门如此受欢迎的编程语…

下载Jakarta

百度找到Jakarta的官网 https://jakarta.ee/zh/ 打开后在右上角有这两个按钮 其中starter按钮是 提供helloworld的&#xff0c;也就是【初体验】&#xff0c;可以根据版本号&#xff0c;jdk版本定制hello world&#xff1b; 另一个Download是下载【兼容产品】&#xff0c;点进…

Python合并多个相交矩形框

Python合并多个相交矩形框 前言前提条件相关介绍实验环境Python合并多个相交矩形框代码实现 前言 由于本人水平有限&#xff0c;难免出现错漏&#xff0c;敬请批评改正。更多精彩内容&#xff0c;可点击进入Python日常小操作专栏、YOLO系列专栏、自然语言处理专栏或我的个人主页…

小程序设计基本微信小程序的旅游社系统

项目介绍 现今市面上有关于旅游信息管理的微信小程序还是比较少的&#xff0c;所以本课题想对如今这么多的旅游景区做一个收集和分类。这样可以给身边喜欢旅游的朋友更好地推荐分享适合去旅行的地方。 前端采用HTML架构&#xff0c;遵循HTMLss JavaScript的开发方式&#xff0…

自动化测试框架指南

目录 定义测试自动化 不同类型的框架 以工具为中心的框架 面向项目的框架 关键字驱动的框架 完美测试自动化框架的主要组件 测试库 单元测试 集成和端到端测试 行为驱动开发 测试数据管理 mock&#xff0c;Stubs和虚拟化 实施模式的通用机制 测试结果报告 CI平台…

SpringBoot+自定义注解+AOP高级玩法打造通用开关

1.项目结构 2.引入依赖 <dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot<…

英特尔 SGX 技术概述

目录 介绍概述指示结构Memory安全区页面缓存Enclave Page Cache &#xff08;EPC&#xff09;安全区页面缓存映射Enclave Page Cache Map (EPCM) Memory ManagementStructures页面信息Page Information (PAGEINFO)安全信息Security Information (SECINFO)分页加密元数据Paging …

ardupilot开发 --- 起飞前后 篇

起飞前检查 电机响应是否正确&#xff08;转向&#xff09;姿态响应是否正常&#xff08;roll pitch yaw&#xff09;GPS数据是否正常&#xff08;星数&#xff0c;RTK信号&#xff09;电源电压安全开关安全检测&#xff08;armed pre check&#xff09; 起飞前的必调参数 机…

SpringCloud 完整版--(Spring Cloud Netflix 体系)

目录 SpringCloudSpring Cloud Netflix 体系分布式概念&#xff1a;分析图单体应用分布式架构集群微服务分布式微服务集群 服务注册与发现Eureka作用&#xff1a;为什么使用Eureka&#xff1f;解答&#xff1a;分析图 搭建&#xff1a;1、注册中心Eureka-server搭建创建项目配置…

springboot苍穹外卖实战:三、新增员工(JWT令牌校验失败+用户名重复+ThreadLocal获取用户id解决方案)

新增员工 根据前端传递参数列表设计DTO 当前端提交的数据和实体类中对应的属性差别比较大时&#xff0c;建议使用DTO来封装数据。进入sky-pojo模块&#xff0c;在com.sky.dto包下&#xff0c;已定义EmployeeDTO。 EmployeeController /*** 新增员工* param employeeDTO* ret…

检测密码安全强度 和 凯撒加密

检测密码安全强度 按照含有数字,小写字母,大写字母,指定标点符号的种类,把安全强度分为强密码,中高,中低,弱密码. 编写程序,输入一个字符串,输出该字符串作为密码时的安全强度 from string import digits, ascii_lowercase, ascii_uppercasedef check(pwd):# 密码必须至少包含…

【前端学习】—使用多种方式实现数组去重(六)

【前端学习】—使用多种方式实现数组去重(六) 一、数组常用的几个方法 //[1,2,3,4,2,1]//[{name:"caicai",age:"10"},{name:"zhangsan",age:"20"}]const array=[

jmeter监听每秒点击数(Hits per Second)

jmeter监听每秒点击数&#xff08;Hits per Second&#xff09; 下载插件添加监听器执行压测&#xff0c;监听结果 下载插件 点击选项&#xff0c;点击Plugins Manager (has upgrades)&#xff0c;点击Available Plugins&#xff0c;搜索5 Additional Graphs安装。 添加监听…

C++新经典 | C++ 查漏补缺(内存)

目录 一、new和delete 1.new类对象时&#xff0c;括号问题 2.new做了什么事 3.delete做了什么事 4.new与malloc的区别 5.delete与free的区别 二、分配及释放内存 三、重载operator new和operator delete操作符 1.重载类中的operator new和operator delete操作符 &…

通信系统中ZF,ML,MRC以及MMSE四种信号检测算法误码率matlab对比仿真

目录 1.算法运行效果图预览 2.算法运行软件版本 3.部分核心程序 4.算法理论概述 4.1、ZF&#xff08;零迫&#xff09;算法 4.2、ML&#xff08;最大似然&#xff09;算法 4.3、MRC&#xff08;最大比合并&#xff09;算法 4.4、MMSE&#xff08;最小均方误差&#xff…

2024杭州人工智能展会(世亚智博会)一场人工智能领域的视觉盛宴

2024年&#xff0c;一场规模空前的人工智能盛会将在杭州国际博览中心盛大开幕。这场名为“2024杭州国际人工智能展览会&#xff08;简称&#xff1a;世亚智博会&#xff09;”的展会活动&#xff0c;将于4月份在杭州国际博览中心隆重举行&#xff0c;届时将迎来一场人工智能领域…

网络安全必备常识:Web应用防火墙是什么?

如今&#xff0c;很多企业都将应用架设在Web平台上&#xff0c;为用户提供更为方便、快捷的服务支持&#xff0c;例如网上银行、网上购物等。与此同时&#xff0c;应用程序组合变得前所未有的复杂和多样化&#xff0c;这为攻击者发动攻击开辟了大量媒介&#xff0c;Web应用防火…

【C++ 学习 ㉘】- 详解 C++11 的列表初始化

目录 一、C11 简介 二、列表初始化 2.1 - 统一初始化 2.2 - 列表初始化的使用细节 2.2.1 - 聚合类型的定义 2.2.2 - 注意事项 2.3 - initializer_list 2.3.1 - 基本使用 2.3.2 - 源码剖析 一、C11 简介 1998 年&#xff0c;C 标准委员会发布了第一版 C 标准&#xff0…

使用new创建动态结构

在运行时创建数组优于在编译时创建数组&#xff0c;对于结构&#xff08;同一个结构可以存储多种类型的数据。&#xff09;也是如此。需要在程序运行时为结构分配所需的空间&#xff0c;这也可以使用new运算符来完成。通过使用new&#xff0c;可以创建动态结构。同样&#xff0…