当前位置: 首页 > 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&…...

深入理解Sentinel: 02 为什么需要服务降级以及常见的几种降级方式

为什么需要服务降级&#xff0c;常见的降级方式有哪些&#xff1f;上一篇跟大家分享了一个真实的服务雪崩的故事&#xff0c;也分析了造成服务雪崩的真正原因&#xff0c;那么&#xff0c;如何才能避免服务雪崩的出现呢&#xff1f;我知道你会说&#xff1a;增加硬件&#xff0…...

如何通过Excel表格可视化实现AI算法的直观理解

如何通过Excel表格可视化实现AI算法的直观理解 【免费下载链接】ai-by-hand-excel 项目地址: https://gitcode.com/gh_mirrors/ai/ai-by-hand-excel 面向AI学习者的可视化数学原理学习工具 当你第一次接触Transformer或LSTM等AI算法时&#xff0c;是否曾被复杂的数学公…...

Keil MDK5.34安装包+破解工具一站式配置指南(附资源下载链接)

Keil MDK5.34 从零配置到项目实战全流程指南 开发环境搭建基础篇 对于刚接触嵌入式开发的工程师来说&#xff0c;Keil MDK作为ARM架构的主流开发工具链&#xff0c;其安装配置往往是第一个需要跨越的门槛。不同于普通软件的"下一步式"安装&#xff0c;MDK环境搭建涉及…...

Kettle转换里SQL步骤优先级太高?手把手教你用‘阻塞数据’控件实现‘先删后插’

Kettle转换中SQL步骤优先级问题深度解析&#xff1a;如何精准控制"先删后插"流程 在ETL开发领域&#xff0c;Kettle&#xff08;现称Pentaho Data Integration&#xff09;因其可视化操作和强大功能成为众多数据工程师的首选工具。然而&#xff0c;当开发者从简单的数…...

Moises vs 其他AI分离工具深度横评:2024年音乐人该如何选择?

Moises vs 其他AI分离工具深度横评&#xff1a;2024年音乐人该如何选择&#xff1f; 当一段复杂的交响乐录音需要提取单簧管声部&#xff0c;或是直播现场需要实时消除伴奏保留人声&#xff0c;音乐人面临的工具选择从未像今天这样丰富而令人困惑。2024年的AI音频分离领域已从早…...

KubeRay实战指南:在Kubernetes上轻松部署和管理Ray应用

KubeRay实战指南&#xff1a;在Kubernetes上轻松部署和管理Ray应用 【免费下载链接】kuberay A toolkit to run Ray applications on Kubernetes 项目地址: https://gitcode.com/GitHub_Trending/ku/kuberay KubeRay是一个强大的开源Kubernetes运算符&#xff0c;专门为…...

音乐“换装”魔法:一文读懂音频生成中的风格迁移技术

音乐“换装”魔法&#xff1a;一文读懂音频生成中的风格迁移技术 引言 想象一下&#xff0c;将一段简单的钢琴旋律&#xff0c;瞬间转换为具有周杰伦特色的中国风R&B&#xff0c;或是恢弘的史诗级电影配乐。这不再是音乐家的专属魔法&#xff0c;而是音频生成与音乐风格迁移…...

机械臂视觉标定进阶:如何用Python脚本自动化处理JAKA机械臂的标定数据

机械臂视觉标定进阶&#xff1a;Python脚本自动化处理JAKA机械臂标定数据全攻略 在工业自动化领域&#xff0c;机械臂的视觉标定精度直接决定了整个系统的作业质量。传统手动标定方法不仅耗时费力&#xff0c;而且难以保证批次间的一致性。本文将分享一套基于Python的自动化标定…...

Phi-4-Reasoning-Vision惊艳效果:低光照/模糊图像中的关键信息增强推理

Phi-4-Reasoning-Vision惊艳效果&#xff1a;低光照/模糊图像中的关键信息增强推理 1. 专业级多模态推理工具介绍 Phi-4-Reasoning-Vision是一款基于微软Phi-4-reasoning-vision-15B多模态大模型开发的高性能推理工具。这个工具专为双卡RTX 4090环境优化&#xff0c;能够处理…...

技术架构驱动的量化交易系统构建:从环境搭建到策略落地全指南

技术架构驱动的量化交易系统构建&#xff1a;从环境搭建到策略落地全指南 【免费下载链接】vnpy 基于Python的开源量化交易平台开发框架 项目地址: https://gitcode.com/vnpy/vnpy 在金融科技快速发展的今天&#xff0c;量化交易系统已成为机构和专业交易者的核心竞争力…...