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

js中的new方法

new方法的作用&#xff1a;创建一个实例对象&#xff0c;并继承原对象的属性和方法&#xff1b; new对象内部操作&#xff1a; 1&#xff0c;创建一个新对象&#xff0c;将新对象的proto属性指向原对象的prototype属性&#xff1b; 2&#xff0c;构造函数执行环境中的this指向…...

机器学习-无监督算法之降维

降维&#xff1a;将训练数据中的样本从高维空间转换到低维空间&#xff0c;降维是对原始数据线性变换实现的。为什么要降维&#xff1f;高维计算难&#xff0c;泛化能力差&#xff0c;防止维数灾难优点&#xff1a;减少冗余特征&#xff0c;方便数据可视化&#xff0c;减少内存…...

ubuntu20.04下Kafka安装部署及基础使用

Ubuntu安装kafka基础使用 kafka 安装环境基础安装下载kafka解压文件修改配置文件启动kafka创建主题查看主题发送消息接收消息 工具测试kafka Assistant 工具连接测试基础连接连接成功查看topic查看消息查看分区查看消费组 Idea 工具测试基础信息配置信息当前消费组发送消息消费…...

汉得欧洲x甄知科技 | 携手共拓全球化布局,助力出海中企数智化发展

HAND Europe 荣幸获得华为云颁发的 GrowCloud 合作伙伴奖项&#xff0c;进一步巩固了其在企业数字化领域的重要地位。于 2023 年 10 月 5 日&#xff0c;HAND Europe 参加了华为云荷比卢峰会&#xff0c;并因其在全球拓展方面的杰出贡献而荣获 GrowCloud 合作伙伴奖项的认可。 …...

【Javascript保姆级教程】显示类型转换和隐式类型转换

文章目录 前言一、显式类型转换1.1 字符串转换1.2 数字转换1.3 布尔值转换 二、隐式类型转换2.1 数字与字符串相加2.2 布尔值与数字相乘 总结 前言 JavaScript是一种灵活的动态类型语言&#xff0c;这意味着变量的数据类型可以在运行时自动转换&#xff0c;或者通过显式类型转…...

C++算法前缀和的应用:分割数组的最大值的原理、源码及测试用例

分割数组的最大值 相关知识点 C算法&#xff1a;前缀和、前缀乘积、前缀异或的原理、源码及测试用例&#xff1a;付视频课程 二分 过些天整理基础知识 题目 给定一个非负整数数组 nums 和一个整数 m &#xff0c;你需要将这个数组分成 m 个非空的连续子数组。 设计一个算法…...

gitlab自编译 源码下载

网上都是怎么用 gitlab&#xff0c;但是实际开发中有需要针对 gitlab 进行二次编译自定义实现功能的想法。 搜索了网上的资料以及在官网的查找&#xff0c;查到了如下 gitlab 使用 ruby 开发。 gitlab 下载包 gitlab/gitlab-ce - Packages packages.gitlab.com gitlab/gitl…...

SBD(Schottky Barrier Diode)与JBS(Junction Barrier Schottky)

SBD和JBS二极管都是功率二极管&#xff0c;具有单向导电性&#xff0c;在电路中主要用于整流、箝位、续流等应用。两者的主要区别在于结构和性能。 结构 SBD是肖特基二极管的简称&#xff0c;其结构由一个金属和一个半导体形成的金属-半导体结构成。 JBS是结势垒肖特基二极…...

HANA:计算视图-图形化Aggregation组件-踩坑小记(注意事项)

今天遇到在做HANA视图开发的时候&#xff0c;遇到一个事&#xff0c;一直以为是个BUG&#xff0c;可把我气坏了&#xff0c;具体逻辑是这样的&#xff0c;是勇图形化处理的&#xff0c;ACDOCA innerjoin 一个时间维度表&#xff0c;就这么简单&#xff0c;完全按照ACDOCA的主键…...

【milkv】更新rndis驱动

问题 由于windows升级到了11&#xff0c;导致rndis驱动无法识别到。 解决 打开设备管理器&#xff0c;查看网络适配器&#xff0c;没有更新会显示黄色的图标。 右击选择更新驱动...