当前位置: 首页 > news >正文

JDBC增删改查示例

数据库表

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由外部传入,在关闭时候也由外部关闭,不再次方法关闭connpublic 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由外部传入,在关闭时候也由外部关闭,不再次方法关闭connpublic 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由外部传入,在关闭时候也由外部关闭,不再次方法关闭connpublic 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 xxxpublic 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(*)返回LongLong getCount(Connection conn);Date getMaxBirth(Connection conn);
}

接口实现类

public class CustomerDaoImpl extends DBUtils2 implements CustomerDao{@Overridepublic 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;}@Overridepublic int deleteCustomerById(Connection conn, Integer id) {String sql="delete from customers where id=?";int count = update(conn, sql, id);return count;}@Overridepublic 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;}@Overridepublic Customers selectCustomerById(Connection conn, Integer id) {String sql="select * from customers where id=?";Customers customers = selectOne(conn, Customers.class, sql, id);return customers;}@Overridepublic List<Customers> selectAllCustomers(Connection conn) {String sql="select * from customers";List<Customers> list = selectList(conn, Customers.class, sql);return list;}@Overridepublic Long getCount(Connection conn) {String sql="select count(*) from customers";return getValue(conn, sql);}@Overridepublic 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();@Testpublic 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);}}@Testpublic 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);}};@Testpublic 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);}};@Testpublic 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);}};@Testpublic 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(*)返回Longpublic 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);}};@Testpublic 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);}};
}

相关文章:

JDBC增删改查示例

数据库表 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) ) ENGINEInnoDB AUTO_INCREMENT39 DEFAULT CHARSETgb2312;…...

emqx broker安装

emqx broker安装 Emq x百万级开源 MQTT 消息服务器 是基于 Erlang/OTP 语言平台开发 一款完全开源&#xff0c;高可用低时延的百万级分布式物联网 MQTT 5.0 消息服务器 官方地址: https://www.emqx.com/zh Centos7 安装 #下载Centos7 amd64位版本 wget https://www.emqx.c…...

如何选择国产压力测试工具?

随着互联网的飞速发展&#xff0c;软件应用的性能和稳定性变得愈发重要。无论是在线购物网站、社交媒体平台还是移动应用程序&#xff0c;用户都期望能够快速、流畅地访问和使用它们。为了确保应用程序在高负载下仍能够正常运行&#xff0c;压力测试工具变得至关重要。在国内&a…...

基于AT89C51流水花样灯proteus仿真设计

一、仿真原理图&#xff1a; 二、仿真效果图&#xff1a; 三、仿真工程&#xff1a; c51单片机流水灯花样灯proteus仿真设计资源-CSDN文库...

android U广播详解(二)

android U广播详解&#xff08;一&#xff09; 基础代码介绍 广播相关 // 用作单个进程批量分发receivers&#xff0c;已被丢弃 frameworks/base/services/core/java/com/android/server/am/BroadcastReceiverBatch.java // 主要逻辑所在类&#xff0c;包括入队、分发、结束…...

导航守卫的使用记录和beforeEach( )死循环的问题

前置导航守卫beforeEach的使用 import Vue from vue import VueRouter from vue-router // 进度条 import NProgress from nprogress import nprogress/nprogress.cssVue.use(VueRouter)// 路由表 const routes [{path: "/",redirect: "/home",},{path: …...

SpringMVC源码分析(三)HandlerExceptionResolver启动和异常处理源码分析

问题&#xff1a;异常处理器在SpringMVC中是如何进行初始化以及使用的&#xff1f; Spring MVC提供处理异常的方式主要分为两种&#xff1a; 1、实现HandlerExceptionResolver方式&#xff08;HandlerExceptionResolver是一个接口&#xff0c;在SpringMVC有一些默认的实现也可以…...

系统架构与Tomcat的安装和配置

2023.10.16 今天是学习javaweb的第一天&#xff0c;主要学习了系统架构的相关知识和原理&#xff0c;下载了web服务器软件&#xff1a;Tomcat&#xff0c;并对其进行了配置。 系统架构 包括&#xff1a;C/S架构 和 B/S架构。 C/S架构&#xff1a; Client / Server&#xff0…...

【Shell脚本】根据起止日期获取Alert日志内容

【Shell脚本】根据起止日期获取Alert日志内容 根据输入的起止日期字符串&#xff0c;检索Oracle告警日志&#xff0c;打印中间的日志行内容。 #!/bin/bash # $1 START_TIME_STR, e.g. "Oct 17 07:" # $2 END_TIME_STR, e.g. "Oct 17 08:" source /home/o…...

Library projects cannot set applicationId. applicationId is set to

Library projects cannot set applicationId. applicationId is set to com.xxx.library_cache in default config. 删掉即可...

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

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

用户行为数据案例

一、环境要求 HadoopHiveSparkHBase 开发环境。 二、数据描述 本数据集包含了2017-09-11至2017-12-03之间有行为的约5458位随机用户的所有行为&#xff08;行为包括点击、购买、加购、喜欢&#xff09;。数据集的每一行表示一条用户行为&#xff0c;由用户ID、商品ID、商品类…...

selenium教程 —— css定位

说明&#xff1a;本篇博客基于selenium 4.1.0 selenium-css定位 element_css driver.find_element(By.CSS_SELECTOR, css表达式) 复制代码 css定位说明 selenium中的css定位&#xff0c;实际是通过css选择器来定位到具体元素&#xff0c;css选择器来自于css语法 css定位优点…...

Leetcode 1834. Single-Threaded CPU (堆好题)

Single-Threaded CPU Medium You are given n​​​​​​ tasks labeled from 0 to n - 1 represented by a 2D integer array tasks, where tasks[i] [enqueueTimei, processingTimei] means that the i​​​​​​th​​​​ task will be available to process at enque…...

21-数据结构-内部排序-交换排序

简介&#xff1a;主要根据两个数据进行比较从而交换彼此位置&#xff0c;以此类推&#xff0c;交换完全部。主要有冒泡和快速排序两种。 目录 一、冒泡排序 1.1简介&#xff1a; 1.2代码&#xff1a; 二、快速排序 1.1简介&#xff1a; 1.2代码&#xff1a; 一、冒泡排序…...

5-k8s-探针介绍

文章目录 一、探针介绍二、探针类型三、探针定义方式四、探针实例五、启动探针测试六、存活探针测试七、就绪探针测试 一、探针介绍 概念 在 Kubernetes 中 Pod 是最小的计算单元&#xff0c;而一个 Pod 又由多个容器组成&#xff0c;相当于每个容器就是一个应用&#xff0c;应…...

【网络安全 --- MySQL数据库】网络安全MySQL数据库应该掌握的知识,还不收藏开始学习。

四&#xff0c;MySQL 4.1 mysql安装 #centos7默认安装的是MariaDB-5.5.68或者65&#xff0c; #查看版本的指令&#xff1a;[rootweb01 bbs]# rpm -qa| grep mariadb #安装mariadb的最新版&#xff0c;只是更新了软件版本&#xff0c;不会删除之前原有的数据。 #修改yum源的配…...

【MyBatis系列】- 什么是MyBatis

【MyBatis系列】- 什么是MyBatis 文章目录 【MyBatis系列】- 什么是MyBatis一、学习MyBatis知识必备1.1 学习环境准备1.2 学习前掌握知识二、什么是MyBatis三、持久层是什么3.1 为什么需要持久化服务3.2 持久层四、Mybatis的作用五、MyBatis的优点六、参考文档一、学习MyBatis知…...

【Linux】Ubuntu美化bash【教程】

【Linux】Ubuntu美化bash【教程】 文章目录 【Linux】Ubuntu美化bash【教程】1. 查看当前环境中是否有bash2. 安装Synth-Shell3. 配置Synth-Shell4. 取消greeterReference 1. 查看当前环境中是否有bash 查看当前使用的bash echo $SHELL如下所示 sjhsjhR9000X:~$ echo $SHELL…...

微信小程序仿苹果负一屏由弱到强的高斯模糊

进入下面小程序可以体验效果&#xff0c;然后进入更多。查看模糊效果 一、创建小程序组件 二、代码 wxml: <view class"topBar-15"></view> <view class"topBar-14"></view> <view class"topBar-13"></view&…...

cf2117E

原题链接&#xff1a;https://codeforces.com/contest/2117/problem/E 题目背景&#xff1a; 给定两个数组a,b&#xff0c;可以执行多次以下操作&#xff1a;选择 i (1 < i < n - 1)&#xff0c;并设置 或&#xff0c;也可以在执行上述操作前执行一次删除任意 和 。求…...

零基础设计模式——行为型模式 - 责任链模式

第四部分&#xff1a;行为型模式 - 责任链模式 (Chain of Responsibility Pattern) 欢迎来到行为型模式的学习&#xff01;行为型模式关注对象之间的职责分配、算法封装和对象间的交互。我们将学习的第一个行为型模式是责任链模式。 核心思想&#xff1a;使多个对象都有机会处…...

Linux 中如何提取压缩文件 ?

Linux 是一种流行的开源操作系统&#xff0c;它提供了许多工具来管理、压缩和解压缩文件。压缩文件有助于节省存储空间&#xff0c;使数据传输更快。本指南将向您展示如何在 Linux 中提取不同类型的压缩文件。 1. Unpacking ZIP Files ZIP 文件是非常常见的&#xff0c;要在 …...

【JavaSE】多线程基础学习笔记

多线程基础 -线程相关概念 程序&#xff08;Program&#xff09; 是为完成特定任务、用某种语言编写的一组指令的集合简单的说:就是我们写的代码 进程 进程是指运行中的程序&#xff0c;比如我们使用QQ&#xff0c;就启动了一个进程&#xff0c;操作系统就会为该进程分配内存…...

4. TypeScript 类型推断与类型组合

一、类型推断 (一) 什么是类型推断 TypeScript 的类型推断会根据变量、函数返回值、对象和数组的赋值和使用方式&#xff0c;自动确定它们的类型。 这一特性减少了显式类型注解的需要&#xff0c;在保持类型安全的同时简化了代码。通过分析上下文和初始值&#xff0c;TypeSc…...

springboot 日志类切面,接口成功记录日志,失败不记录

springboot 日志类切面&#xff0c;接口成功记录日志&#xff0c;失败不记录 自定义一个注解方法 import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target;/***…...

在鸿蒙HarmonyOS 5中使用DevEco Studio实现指南针功能

指南针功能是许多位置服务应用的基础功能之一。下面我将详细介绍如何在HarmonyOS 5中使用DevEco Studio实现指南针功能。 1. 开发环境准备 确保已安装DevEco Studio 3.1或更高版本确保项目使用的是HarmonyOS 5.0 SDK在项目的module.json5中配置必要的权限 2. 权限配置 在mo…...

图解JavaScript原型:原型链及其分析 | JavaScript图解

​​ 忽略该图的细节&#xff08;如内存地址值没有用二进制&#xff09; 以下是对该图进一步的理解和总结 1. JS 对象概念的辨析 对象是什么&#xff1a;保存在堆中一块区域&#xff0c;同时在栈中有一块区域保存其在堆中的地址&#xff08;也就是我们通常说的该变量指向谁&…...

AD学习(3)

1 PCB封装元素组成及简单的PCB封装创建 封装的组成部分&#xff1a; &#xff08;1&#xff09;PCB焊盘&#xff1a;表层的铜 &#xff0c;top层的铜 &#xff08;2&#xff09;管脚序号&#xff1a;用来关联原理图中的管脚的序号&#xff0c;原理图的序号需要和PCB封装一一…...

归并排序:分治思想的高效排序

目录 基本原理 流程图解 实现方法 递归实现 非递归实现 演示过程 时间复杂度 基本原理 归并排序(Merge Sort)是一种基于分治思想的排序算法&#xff0c;由约翰冯诺伊曼在1945年提出。其核心思想包括&#xff1a; 分割(Divide)&#xff1a;将待排序数组递归地分成两个子…...