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

Spring整合JDBC

1、引入依赖

 <properties><maven.compiler.source>8</maven.compiler.source><maven.compiler.target>8</maven.compiler.target><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties><dependencies><!--  测试依赖   --><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version><scope>test</scope></dependency><!--核心依赖--><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>5.2.13.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-jdbc</artifactId><version>5.2.13.RELEASE</version></dependency>
<!--        mysql依赖--><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.29</version></dependency>
<!--        数据源依赖--><dependency><groupId>com.mchange</groupId><artifactId>c3p0</artifactId><version>0.9.5.2</version></dependency></dependencies><build><plugins>
<!--            编译插件    --><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId><version>3.8.0</version><configuration><source>1.8</source><target>1.8</target></configuration></plugin></plugins></build>

2、测试连接

连接数据库并且操作的步骤如下 ,连接对应的数据库,前提是本机中存在mysql并且运行以及创建对应的数据库。

然后将四大参数放入,在DriverClass参数中mysql8以上才会由中间的.cj.,8以下没有。url中数据库问号后的内容为字符集的相关设置。

然后通过JdbcTemplate可以对数据库进行相关的操作

 @Testpublic void test01( ) throws PropertyVetoException {// 创建数据库ComboPooledDataSource dataSource = new ComboPooledDataSource();dataSource.setDriverClass("com.mysql.cj.jdbc.Driver");dataSource.setJdbcUrl("jdbc:mysql://127.0.0.1:3306/springJDBC?serverTimezone=Asia/Shanghai&characterEncoding=utf8&useUnicode=true&useSSL=false");dataSource.setUser("root");dataSource.setPassword("123456");// 使用JdbcTemplate template = new JdbcTemplate(dataSource);String sql = "INSERT INTO team (tname , location) VALUES (?, ?)";int update = template.update(sql, "AI2", "郑州2");System.out.println("插入结果: " + update);}

 3、spring管理JdbcTemplate

spring整合jdbc可以让dao层继承Spring提供的JdbcDaoSupport类,该类中提供了jdbcTemplate模板可以用来使用。

handlResult函数:是因为在查找的操作中,由重复性的操作,单独拿出来进行封装,用来简化代码。

非查找语句的执行中,都是通过调用JdbcTemplate中的update函数,第一个参数为sql语句,后面跟不定量的参数用来填补sql语句中占位符的位置。

查找语句
        返回数据只有一行的时候使用qyeryForObject函数,第一个位置为sql语句,第二个Object数组内容为参数,用来填补占位符,第三个位置为RowMapper接口用来处理返回的每一行数据,处理结果为需要的数据类型。
        返回数据有多行的情况使用query函数,参数类型同上,区别就是query函数的返回值类型为list数组。
        返回数据只有一列的情况,第二个参数可以直接用对应类型的类。
        返回数据只有一行的情况,并且不是一个类等,可以用Map来存取返回值,使用qyeryForMay,第一个位置为sql语句,第二个Object数组内容为参数,用来填补占位符。

public class TeamDao extends JdbcDaoSupport {public Team handlResult(ResultSet resultSet) throws SQLException {Team team = new Team();team.settId(resultSet.getInt("tid"));team.setLocation(resultSet.getString("location"));team.settName(resultSet.getString("tname"));return team;}public int insert(Team team) {String sql = "insert team (tname, location) values (?, ?)";int update = this.getJdbcTemplate().update(sql, team.gettName(), team.getLocation());return update;}public int update(Team team) {String sql = "update team set tname=?, location=? where tid=?";return this.getJdbcTemplate().update(sql, team.gettName(), team.getLocation(), team.gettId());}public int del(int id) {String sql = "delete from team where tid=?";return this.getJdbcTemplate().update(sql, id);}public Team getTeamById(int id) {String sql = "select * from team where tid=?";Team team = (Team) this.getJdbcTemplate().queryForObject(sql, new Object[] {id}, new RowMapper<Object>() {@Overridepublic Object mapRow(ResultSet resultSet, int i) throws SQLException {return handlResult(resultSet);}});return team;}public List<Team> getTeamAll() {String sql = "select * from team";List<Team> list = this.getJdbcTemplate().query(sql, new RowMapper<Team>() {@Overridepublic Team mapRow(ResultSet resultSet, int i) throws SQLException {return handlResult(resultSet);}});return list;}public int getCount() {String sql = "select count(*) from team";// 如果查询的列只有唯一一列,queryForObject (sql语句,为一列的数据类型)return this.getJdbcTemplate().queryForObject(sql,  Integer.class);}public Map<String, Object> getMany() {String sql = "select max(tid) as max, min(tid) as min from team";// 如果查询的列只有唯一一列,queryForObject (sql语句,为一列的数据类型)return this.getJdbcTemplate().queryForMap(sql);}
}

spring的配置文件application.xml中需要创建数据源和给TeamDao中的jdbcTemplate赋值

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
"><!-- 创建数据源 --><bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"><property name="driverClass" value="com.mysql.cj.jdbc.Driver"/><property name="jdbcUrl" value="jdbc:mysql://127.0.0.1:3306/springJDBC?serverTimezone=Asia/Shanghai&amp;characterEncoding=utf8&amp;useUnicode=true&amp;useSSL=false"/><property name="user" value="root"/><property name="password" value="123456"/></bean><!-- 创建jdbcTemplate对象,给类中dataSource赋值 --><bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"><property name="dataSource" ref="dataSource"></property></bean><!-- 创建teamDao对象,给类中jdbcTemplate赋值 --><bean id="teamDao" class="com.AE.dao.TeamDao"><property name="jdbcTemplate" ref="jdbcTemplate"/></bean>
</beans>

4、测试

public class test01 {
//    private TeamDao teamDao;@Testpublic void test01( ) throws PropertyVetoException {// 创建数据库ComboPooledDataSource dataSource = new ComboPooledDataSource();dataSource.setDriverClass("com.mysql.cj.jdbc.Driver");dataSource.setJdbcUrl("jdbc:mysql://127.0.0.1:3306/springJDBC?serverTimezone=Asia/Shanghai&characterEncoding=utf8&useUnicode=true&useSSL=false");dataSource.setUser("root");dataSource.setPassword("123456");// 使用JdbcTemplate template = new JdbcTemplate(dataSource);String sql = "INSERT INTO team (tname , location) VALUES (?, ?)";int update = template.update(sql, "AI2", "郑州2");System.out.println("插入结果: " + update);}@Testpublic void test02(){ApplicationContext ac = new ClassPathXmlApplicationContext("spring.xml");TeamDao teamDao = (TeamDao) ac.getBean("teamDao");Team team = new Team();team.setLocation("南阳");team.settName("张淏");int insert = teamDao.insert(team);System.out.println(insert);}@Testpublic void test03(){ApplicationContext ac = new ClassPathXmlApplicationContext("spring.xml");TeamDao teamDao = (TeamDao) ac.getBean("teamDao");Team team = new Team();team.settId(5);team.setLocation("郑州3");team.settName("AI3");int update = teamDao.update(team);System.out.println(update);}@Testpublic void test04(){ApplicationContext ac = new ClassPathXmlApplicationContext("spring.xml");TeamDao teamDao = (TeamDao) ac.getBean("teamDao");int update = teamDao.del(5);System.out.println(update);}@Testpublic void test05(){ApplicationContext ac = new ClassPathXmlApplicationContext("spring.xml");TeamDao teamDao = (TeamDao) ac.getBean("teamDao");Team team = teamDao.getTeamById(2);System.out.println(team);}@Testpublic void test06(){ApplicationContext ac = new ClassPathXmlApplicationContext("spring.xml");TeamDao teamDao = (TeamDao) ac.getBean("teamDao");List<Team> list = teamDao.getTeamAll();for(Team team : list) {System.out.println(team);}System.out.println(list);}@Testpublic void test07(){ApplicationContext ac = new ClassPathXmlApplicationContext("spring.xml");TeamDao teamDao = (TeamDao) ac.getBean("teamDao");int a = teamDao.getCount();System.out.println(a);}@Testpublic void test08(){ApplicationContext ac = new ClassPathXmlApplicationContext("spring.xml");TeamDao teamDao = (TeamDao) ac.getBean("teamDao");Map<String, Object> many = teamDao.getMany();for(String a : many.keySet()) {System.out.println(a + "=" + many.get(a));}}
}

相关文章:

Spring整合JDBC

1、引入依赖 <properties><maven.compiler.source>8</maven.compiler.source><maven.compiler.target>8</maven.compiler.target><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties><depen…...

详解Qt中的布局管理器

Qt中的布局管理是用于组织用户界面中控件&#xff08;如按钮、文本框、标签等&#xff09;位置和尺寸调整的一种机制。说白了就是创建了一种规则&#xff0c;随着窗口变化其中的控件大小位置跟着变化。Qt提供了多种布局管理器&#xff0c;每种都有其特定用途和特点。以下是对Qt…...

MyBatis 参数重复打印的bug

现象 最近有个需求&#xff0c;需要在mybatis对数据库进行写入操作的时候&#xff0c;根据条件对对象中的某个值进行置空&#xff0c;然后再进行写入&#xff0c;这样数据库中的值就会为空了。 根据网上查看的资料&#xff0c;选择在 StatementHandler 类执行 update 的时候进…...

ES6学习之路:迭代器Iterator和生成器Generator

迭代器 一、知识背景 什么是迭代器 迭代器就是在一个数据集合中不断取出数据的过程迭代和遍历的区别 遍历是把所有数据都取出迭代器注重的是依次取出数据&#xff0c;它不会在意有多少数据&#xff0c;也不会保证能够取出多少或者能够把数据都取完。比如斐波那契额数列&#…...

如何使用 DynamiCrafter Interp Loop 无缝连接两张照片

DynamiCrafter Interp Loop 是一个基于 AI 的工具&#xff0c;可以用来无缝连接两张照片。它使用深度学习技术来生成中间帧&#xff0c;从而使两张照片之间的过渡更加自然流畅。 使用步骤 访问 DynamiCrafter Interp Loop 网站&#xff1a;https://huggingface.co/spaces/Dou…...

今天起,Windows可以一键召唤GPT-4了

ChatGPT狂飙160天&#xff0c;世界已经不是之前的样子。 新建了人工智能中文站https://ai.weoknow.com 每天给大家更新可用的国内可用chatGPT资源 发布在https://it.weoknow.com 更多资源欢迎关注 微软 AI 大计的最后一块拼图完成了&#xff1f; 把 Copilot 按钮放在 Window…...

使用Kaggle API快速下载Kaggle数据集

前言 在使用Kaggle网站下载数据集时&#xff0c;直接在网页上点击下载可能会很慢&#xff0c;甚至会出现下载失败的情况。本文将介绍如何使用Kaggle API快速下载数据集。 具体步骤 安装Kaggle API包 在终端中输入以下命令来安装Kaggle API相关的包&#xff1a; pip install…...

java 通过 microsoft graph 调用outlook(二)

这次提供一些基础调用方式API PS&#xff1a; getMailFolders 接口返回的属性中&#xff0c;包含了未读邮件数量unreadItemCount 一 POM文件 <!-- office 365 --><dependency><groupId>com.google.guava</groupId><artifactId>guava<…...

【机器学习】代价函数

&#x1f388;个人主页&#xff1a;豌豆射手^ &#x1f389;欢迎 &#x1f44d;点赞✍评论⭐收藏 &#x1f917;收录专栏&#xff1a;机器学习 &#x1f91d;希望本文对您有所裨益&#xff0c;如有不足之处&#xff0c;欢迎在评论区提出指正&#xff0c;让我们共同学习、交流进…...

[leetcode] 100. 相同的树

给你两棵二叉树的根节点 p 和 q &#xff0c;编写一个函数来检验这两棵树是否相同。 如果两个树在结构上相同&#xff0c;并且节点具有相同的值&#xff0c;则认为它们是相同的。 示例 1&#xff1a; 输入&#xff1a;p [1,2,3], q [1,2,3] 输出&#xff1a;true示例 2&a…...

08、Lua 函数

Lua 函数 Lua 函数Lua函数主要有两种用途函数定义解析&#xff1a;optional_function_scopefunction_nameargument1, argument2, argument3..., argumentnfunction_bodyresult_params_comma_separated 范例 : 定义一个函数 max()Lua 中函数可以作为参数传递给函数多返回值Lua函…...

【数据分析面试】1. 计算年度收入百分比(SQL)

题目 你需要为公司的营收来源生成一份年度报告。计算截止目前为止&#xff0c;在表格中记录的第一年和最后一年所创造的总收入百分比。将百分比四舍五入到两位小数。 示例&#xff1a; 输入&#xff1a; annual_payments 表 列名类型amountINTEGERcreated_atDATETIMEstatusV…...

数据库SQL语句速查手册

SQL 语句语法AND / ORSELECT column_name(s) FROM table_name WHERE condition AND|OR conditionALTER TABLEALTER TABLE table_name ADD column_name datatypeorALTER TABLE table_name DROP COLUMN column_nameAS (alias)SELECT column_name AS column_alias FROM table_name…...

智慧城市一屏统览,数字孪生综合治理

现代城市作为一个复杂系统&#xff0c;牵一发而动全身&#xff0c;城市化进程中产生新的矛盾和社会问题都会影响整个城市系统的正常运转。智慧城市是应对这些问题的策略之一。城市工作要树立系统思维&#xff0c;从构成城市诸多要素、结构、功能等方面入手&#xff0c;系统推进…...

Python读取PDF文字转txt,解决分栏识别问题,能读两栏

搜索了一下&#xff0c;大致有这些库能将PDF转txt 1. PyPDF/PyPDF2&#xff08;截止2024.03.28这两个已经合并成了一个&#xff09;pypdf PyPI 2. pdfplumber GitHub - jsvine/pdfplumber: Plumb a PDF for detailed information about each char, rectangle, line, et cete…...

微信支付平台与微信服务号关联配置要点

目录 JSAPI支付 前期资料及相关准备 申请微信服务号 服务号配置要点 微信认证 基本配置 功能设置 申请微信支付号 支付号配置要点 设置操作密码 API安全 开发设置 与服务号关联 小结 JSAPI支付 我们的开发应用场景以JSAPI支付为举例&#xff0c;这也是常用的一…...

C++类复习

C类 1. 类内成员函数隐式声明为inline class Str {int x;int y 3; public:inline void fun(){std::cout<<"pf,yes!"<<std::endl;} };这段代码不会报错&#xff0c;但是类内的成员函数隐式声明为inline函数&#xff0c;不需要单独写在前面。因此将成员…...

Spring使用(一)注解

Spring使用 资源 Spring 框架内部使用 Resource 接口作为所有资源的抽象和访问接口&#xff0c;在上一篇文章的示例代码中的配置文件是通过ClassPathResource 进行封装的&#xff0c;ClassPathResource 是 Resource 的一个特定类型的实现&#xff0c;代表的是位于 classpath …...

Linux基本指令篇

在前边&#xff0c;我们已经了解过了Linux操作系统的发展和应用&#xff0c;从该篇起&#xff0c;就正式进入对Linux的学习。 今天我们就来在Xshell上远程登录我们的云服务器。首先我们要知道自己云服务器的公网ip&#xff0c;然后修改一下密码。 点击跳转 修改完密码之后我们…...

CSS实现小车旅行动画实现

小车旅行动画实现 效果展示 CSS 知识点 灵活使用 background 属性下的 repeating-linear-gradient 实现路面效果灵活运用 animation 属性与 transform 实现小车和其他元素的动画效果 动画场景分析 从效果图可以看出需要实现此动画的话&#xff0c;需要position属性控制元素…...

51c自动驾驶~合集58

我自己的原文哦~ https://blog.51cto.com/whaosoft/13967107 #CCA-Attention 全局池化局部保留&#xff0c;CCA-Attention为LLM长文本建模带来突破性进展 琶洲实验室、华南理工大学联合推出关键上下文感知注意力机制&#xff08;CCA-Attention&#xff09;&#xff0c;…...

《Playwright:微软的自动化测试工具详解》

Playwright 简介:声明内容来自网络&#xff0c;将内容拼接整理出来的文档 Playwright 是微软开发的自动化测试工具&#xff0c;支持 Chrome、Firefox、Safari 等主流浏览器&#xff0c;提供多语言 API&#xff08;Python、JavaScript、Java、.NET&#xff09;。它的特点包括&a…...

pam_env.so模块配置解析

在PAM&#xff08;Pluggable Authentication Modules&#xff09;配置中&#xff0c; /etc/pam.d/su 文件相关配置含义如下&#xff1a; 配置解析 auth required pam_env.so1. 字段分解 字段值说明模块类型auth认证类模块&#xff0c;负责验证用户身份&am…...

Linux简单的操作

ls ls 查看当前目录 ll 查看详细内容 ls -a 查看所有的内容 ls --help 查看方法文档 pwd pwd 查看当前路径 cd cd 转路径 cd .. 转上一级路径 cd 名 转换路径 …...

基于当前项目通过npm包形式暴露公共组件

1.package.sjon文件配置 其中xh-flowable就是暴露出去的npm包名 2.创建tpyes文件夹&#xff0c;并新增内容 3.创建package文件夹...

Vue2 第一节_Vue2上手_插值表达式{{}}_访问数据和修改数据_Vue开发者工具

文章目录 1.Vue2上手-如何创建一个Vue实例,进行初始化渲染2. 插值表达式{{}}3. 访问数据和修改数据4. vue响应式5. Vue开发者工具--方便调试 1.Vue2上手-如何创建一个Vue实例,进行初始化渲染 准备容器引包创建Vue实例 new Vue()指定配置项 ->渲染数据 准备一个容器,例如: …...

Robots.txt 文件

什么是robots.txt&#xff1f; robots.txt 是一个位于网站根目录下的文本文件&#xff08;如&#xff1a;https://example.com/robots.txt&#xff09;&#xff0c;它用于指导网络爬虫&#xff08;如搜索引擎的蜘蛛程序&#xff09;如何抓取该网站的内容。这个文件遵循 Robots…...

自然语言处理——循环神经网络

自然语言处理——循环神经网络 循环神经网络应用到基于机器学习的自然语言处理任务序列到类别同步的序列到序列模式异步的序列到序列模式 参数学习和长程依赖问题基于门控的循环神经网络门控循环单元&#xff08;GRU&#xff09;长短期记忆神经网络&#xff08;LSTM&#xff09…...

Map相关知识

数据结构 二叉树 二叉树&#xff0c;顾名思义&#xff0c;每个节点最多有两个“叉”&#xff0c;也就是两个子节点&#xff0c;分别是左子 节点和右子节点。不过&#xff0c;二叉树并不要求每个节点都有两个子节点&#xff0c;有的节点只 有左子节点&#xff0c;有的节点只有…...

排序算法总结(C++)

目录 一、稳定性二、排序算法选择、冒泡、插入排序归并排序随机快速排序堆排序基数排序计数排序 三、总结 一、稳定性 排序算法的稳定性是指&#xff1a;同样大小的样本 **&#xff08;同样大小的数据&#xff09;**在排序之后不会改变原始的相对次序。 稳定性对基础类型对象…...