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&characterEncoding=utf8&useUnicode=true&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中的布局管理是用于组织用户界面中控件(如按钮、文本框、标签等)位置和尺寸调整的一种机制。说白了就是创建了一种规则,随着窗口变化其中的控件大小位置跟着变化。Qt提供了多种布局管理器,每种都有其特定用途和特点。以下是对Qt…...
MyBatis 参数重复打印的bug
现象 最近有个需求,需要在mybatis对数据库进行写入操作的时候,根据条件对对象中的某个值进行置空,然后再进行写入,这样数据库中的值就会为空了。 根据网上查看的资料,选择在 StatementHandler 类执行 update 的时候进…...
ES6学习之路:迭代器Iterator和生成器Generator
迭代器 一、知识背景 什么是迭代器 迭代器就是在一个数据集合中不断取出数据的过程迭代和遍历的区别 遍历是把所有数据都取出迭代器注重的是依次取出数据,它不会在意有多少数据,也不会保证能够取出多少或者能够把数据都取完。比如斐波那契额数列&#…...
如何使用 DynamiCrafter Interp Loop 无缝连接两张照片
DynamiCrafter Interp Loop 是一个基于 AI 的工具,可以用来无缝连接两张照片。它使用深度学习技术来生成中间帧,从而使两张照片之间的过渡更加自然流畅。 使用步骤 访问 DynamiCrafter Interp Loop 网站:https://huggingface.co/spaces/Dou…...
今天起,Windows可以一键召唤GPT-4了
ChatGPT狂飙160天,世界已经不是之前的样子。 新建了人工智能中文站https://ai.weoknow.com 每天给大家更新可用的国内可用chatGPT资源 发布在https://it.weoknow.com 更多资源欢迎关注 微软 AI 大计的最后一块拼图完成了? 把 Copilot 按钮放在 Window…...
使用Kaggle API快速下载Kaggle数据集
前言 在使用Kaggle网站下载数据集时,直接在网页上点击下载可能会很慢,甚至会出现下载失败的情况。本文将介绍如何使用Kaggle API快速下载数据集。 具体步骤 安装Kaggle API包 在终端中输入以下命令来安装Kaggle API相关的包: pip install…...
java 通过 microsoft graph 调用outlook(二)
这次提供一些基础调用方式API PS: getMailFolders 接口返回的属性中,包含了未读邮件数量unreadItemCount 一 POM文件 <!-- office 365 --><dependency><groupId>com.google.guava</groupId><artifactId>guava<…...
【机器学习】代价函数
🎈个人主页:豌豆射手^ 🎉欢迎 👍点赞✍评论⭐收藏 🤗收录专栏:机器学习 🤝希望本文对您有所裨益,如有不足之处,欢迎在评论区提出指正,让我们共同学习、交流进…...
[leetcode] 100. 相同的树
给你两棵二叉树的根节点 p 和 q ,编写一个函数来检验这两棵树是否相同。 如果两个树在结构上相同,并且节点具有相同的值,则认为它们是相同的。 示例 1: 输入:p [1,2,3], q [1,2,3] 输出:true示例 2&a…...
08、Lua 函数
Lua 函数 Lua 函数Lua函数主要有两种用途函数定义解析:optional_function_scopefunction_nameargument1, argument2, argument3..., argumentnfunction_bodyresult_params_comma_separated 范例 : 定义一个函数 max()Lua 中函数可以作为参数传递给函数多返回值Lua函…...
【数据分析面试】1. 计算年度收入百分比(SQL)
题目 你需要为公司的营收来源生成一份年度报告。计算截止目前为止,在表格中记录的第一年和最后一年所创造的总收入百分比。将百分比四舍五入到两位小数。 示例: 输入: 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…...
智慧城市一屏统览,数字孪生综合治理
现代城市作为一个复杂系统,牵一发而动全身,城市化进程中产生新的矛盾和社会问题都会影响整个城市系统的正常运转。智慧城市是应对这些问题的策略之一。城市工作要树立系统思维,从构成城市诸多要素、结构、功能等方面入手,系统推进…...
Python读取PDF文字转txt,解决分栏识别问题,能读两栏
搜索了一下,大致有这些库能将PDF转txt 1. PyPDF/PyPDF2(截止2024.03.28这两个已经合并成了一个)pypdf PyPI 2. pdfplumber GitHub - jsvine/pdfplumber: Plumb a PDF for detailed information about each char, rectangle, line, et cete…...
微信支付平台与微信服务号关联配置要点
目录 JSAPI支付 前期资料及相关准备 申请微信服务号 服务号配置要点 微信认证 基本配置 功能设置 申请微信支付号 支付号配置要点 设置操作密码 API安全 开发设置 与服务号关联 小结 JSAPI支付 我们的开发应用场景以JSAPI支付为举例,这也是常用的一…...
C++类复习
C类 1. 类内成员函数隐式声明为inline class Str {int x;int y 3; public:inline void fun(){std::cout<<"pf,yes!"<<std::endl;} };这段代码不会报错,但是类内的成员函数隐式声明为inline函数,不需要单独写在前面。因此将成员…...
Spring使用(一)注解
Spring使用 资源 Spring 框架内部使用 Resource 接口作为所有资源的抽象和访问接口,在上一篇文章的示例代码中的配置文件是通过ClassPathResource 进行封装的,ClassPathResource 是 Resource 的一个特定类型的实现,代表的是位于 classpath …...
Linux基本指令篇
在前边,我们已经了解过了Linux操作系统的发展和应用,从该篇起,就正式进入对Linux的学习。 今天我们就来在Xshell上远程登录我们的云服务器。首先我们要知道自己云服务器的公网ip,然后修改一下密码。 点击跳转 修改完密码之后我们…...
CSS实现小车旅行动画实现
小车旅行动画实现 效果展示 CSS 知识点 灵活使用 background 属性下的 repeating-linear-gradient 实现路面效果灵活运用 animation 属性与 transform 实现小车和其他元素的动画效果 动画场景分析 从效果图可以看出需要实现此动画的话,需要position属性控制元素…...
调用支付宝接口响应40004 SYSTEM_ERROR问题排查
在对接支付宝API的时候,遇到了一些问题,记录一下排查过程。 Body:{"datadigital_fincloud_generalsaas_face_certify_initialize_response":{"msg":"Business Failed","code":"40004","sub_msg…...
css实现圆环展示百分比,根据值动态展示所占比例
代码如下 <view class""><view class"circle-chart"><view v-if"!!num" class"pie-item" :style"{background: conic-gradient(var(--one-color) 0%,#E9E6F1 ${num}%),}"></view><view v-else …...
椭圆曲线密码学(ECC)
一、ECC算法概述 椭圆曲线密码学(Elliptic Curve Cryptography)是基于椭圆曲线数学理论的公钥密码系统,由Neal Koblitz和Victor Miller在1985年独立提出。相比RSA,ECC在相同安全强度下密钥更短(256位ECC ≈ 3072位RSA…...
C++:std::is_convertible
C++标志库中提供is_convertible,可以测试一种类型是否可以转换为另一只类型: template <class From, class To> struct is_convertible; 使用举例: #include <iostream> #include <string>using namespace std;struct A { }; struct B : A { };int main…...
23-Oracle 23 ai 区块链表(Blockchain Table)
小伙伴有没有在金融强合规的领域中遇见,必须要保持数据不可变,管理员都无法修改和留痕的要求。比如医疗的电子病历中,影像检查检验结果不可篡改行的,药品追溯过程中数据只可插入无法删除的特性需求;登录日志、修改日志…...
Springcloud:Eureka 高可用集群搭建实战(服务注册与发现的底层原理与避坑指南)
引言:为什么 Eureka 依然是存量系统的核心? 尽管 Nacos 等新注册中心崛起,但金融、电力等保守行业仍有大量系统运行在 Eureka 上。理解其高可用设计与自我保护机制,是保障分布式系统稳定的必修课。本文将手把手带你搭建生产级 Eur…...
微服务商城-商品微服务
数据表 CREATE TABLE product (id bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT 商品id,cateid smallint(6) UNSIGNED NOT NULL DEFAULT 0 COMMENT 类别Id,name varchar(100) NOT NULL DEFAULT COMMENT 商品名称,subtitle varchar(200) NOT NULL DEFAULT COMMENT 商…...
c#开发AI模型对话
AI模型 前面已经介绍了一般AI模型本地部署,直接调用现成的模型数据。这里主要讲述讲接口集成到我们自己的程序中使用方式。 微软提供了ML.NET来开发和使用AI模型,但是目前国内可能使用不多,至少实践例子很少看见。开发训练模型就不介绍了&am…...
Linux --进程控制
本文从以下五个方面来初步认识进程控制: 目录 进程创建 进程终止 进程等待 进程替换 模拟实现一个微型shell 进程创建 在Linux系统中我们可以在一个进程使用系统调用fork()来创建子进程,创建出来的进程就是子进程,原来的进程为父进程。…...
JS手写代码篇----使用Promise封装AJAX请求
15、使用Promise封装AJAX请求 promise就有reject和resolve了,就不必写成功和失败的回调函数了 const BASEURL ./手写ajax/test.jsonfunction promiseAjax() {return new Promise((resolve, reject) > {const xhr new XMLHttpRequest();xhr.open("get&quo…...
