0x00 简介
JDBC是Java程序访问数据库的一个接口,它通过调用厂商提供的JDBC Driver来实现对数据库的访问.
但是它操作比较繁琐,先得创建全局DataSource
实例=>再从中获取Connection
实例=>通过Connection
实例创建PreparedStatement
实例=>执行SQL语句
而且每次都得用try-finally
释放资源...
因此Spring对它进行了封装,加入了注入功能,把DataSource注入到JdbcTemplate中,省略数据源的获取.还加入了事务和异常控制,减少了繁琐的异常判断.
0x01 安装mysql
- 下载MySQLMySQL :: Download MySQL Community Server
- 解压到
C:webmysql-8.0.26
- 修改MySQL配置文件
- 在
C:webmysql-8.0.26
文件夹,创建修改my.ini
配置文件 - 编写配置信息
- 在
[client] # 设置mysql客户端默认字符集
default-character-set=utf8
[mysqld]
# 设置3306端口
port = 3306
# 设置mysql的安装目录
basedir=C:webmysql-8.0.26-winx64
# 设置 mysql数据库的数据的存放目录,MySQL 8+ 不需要以下配置,系统自己生成即可,否则有可能报错
#datadir=C:\web\sqldata
# 允许最大连接数
max_connections=20
# 服务端使用的字符集默认为8比特编码的latin1字符集
character-set-server=utf8
# 创建新表时将使用的默认存储引擎
default-storage-engine=INNODB
- 千万记得修改
basedir
为当前目录,否则后续步骤无法正常执行
-
添加
/bin
路径到环境变量
-
启动MySQL数据库
-
以管理员身份打开cmd
-
切换到
/bin
文件夹cd C:webmysql-8.0.26-winx64in
-
初始化数据库
mysqld --initialize --console
-
记录返回的临时密码
-
安装mysql
mysqld install
-
启动mysql服务
net start mysql
-
登入mysql数据库
mysql -u root -p
-
更改密码
alter user'root'@'localhost' identified by 'pass'
%%8. 关闭mysql服务net stop mysql
%%
-
0x02 配置数据源
- 在mysql中创建一个名为spring_db的数据库
create database spring_db
0x03 配置SpringJDBC
- 在idea中创建一个Spring项目
- 配置
pom.xml
文件,导入相关依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>SSM-bootstrap</artifactId>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
<modules>
<module>MyJdbc</module>
</modules>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.6</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.16.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.2.16.RELEASE</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.26</version>
<!-- 版本号必须和数据库相同, 详见参考4-->
</dependency>
</dependencies>
</project>
- 编写配置文件
applicationContext.xml
<?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="org.springframework.jdbc.datasource.DriverManagerDataSource">
<!-- 数据库驱动-->
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<!-- 连接数据库的url-->
<property name="url" value="jdbc:mysql://localhost:3306/spring_db"></property>
<!-- 连接数据库的用户名-->
<property name="username" value="root"></property>
<!-- 连接数据库的密码-->
<property name="password" value="pass"></property>
</bean>
<!-- 配置JDBC模板-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<!-- 引用上面配置的数据源-->
<property name="dataSource" ref="dataSource"></property>
</bean>
</beans>
- 编写测试类
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
public class MyJdbcTest {
public static void main(String[] args) {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");
JdbcTemplate jdbcTemplate = (JdbcTemplate) applicationContext.getBean("jdbcTemplate");
jdbcTemplate.execute(
"create table user("+
"id int primary key auto_increment,"+
"username varchar(40),"+
"password varchar(40))"
);
}
}
- 查看测试结果
运行测试类后,登入数据库发现新表创建成功,说明JDBC配置成功.
0x04 Spring JdbcTemplate的常用方法
4.1 execute()
利用JdbcTemplate的execute()方法执行sql语句,我们在上面已经用过了,这边不再赘述.
4.2 update() 更新数据
- 编写
User
bean
package bean;
public class User {
private Integer id;
private String username;
private String password;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
- 编写
UserDao
和UserDaoImpl
package dao;
import bean.User;
public interface UserDao {
public int addUser(User user);
public int updateUser(User user);
public int deleteUser(int id);
}
package dao;
import bean.User;
import org.springframework.jdbc.core.JdbcTemplate;
public class UserDaoImpl implements UserDao{
private JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
@Override
public int addUser(User user) {
String sql = "insert into user(username,password) value(?,?)";
Object[] obj = new Object[]{
user.getUsername(),
user.getPassword()
};
int retVal = this.jdbcTemplate.update(sql,obj);
return retVal;
}
@Override
public int updateUser(User user) {
String sql = "update user set username=?,password=? where id=?";
Object[] obj = new Object[]{
user.getUsername(),
user.getPassword(),
user.getId()
};
int retVal = this.jdbcTemplate.update(sql,obj);
return retVal;
}
@Override
public int deleteUser(int id) {
String sql = "delete from user where id=?";
int retVal = this.jdbcTemplate.update(sql,id);
return retVal;
}
}
- 注册
UserDaoImpl
到applicationContext.xml
<bean id="userDao" class="dao.UserDaoImpl">
<property name="jdbcTemplate" ref="jdbcTemplate"></property>
</bean>
- 编写测试类(添加用户)
@Test
public void addUserTest(){
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
UserDao userDao = (UserDao) applicationContext.getBean("userDao");
User user = new User();
user.setUsername("foo");
user.setPassword("bar");
int retVal = userDao.addUser(user);
if(retVal>0){
System.out.println("成功插入了" + retVal + "条数据");
}else {
System.out.println("插入操作执行失败");
}
}
-
调试运行后查看数据库
-
编写测试类+调试查看数据库(更新用户)
@Test
public void updateUserTest(){
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
UserDao userDao = (UserDao) applicationContext.getBean("userDao");
User user = new User();
user.setId(1);
user.setUsername("fooo");
user.setPassword("barr");
int retVal = userDao.updateUser(user);
if(retVal>0){
System.out.println("成功更新了" + retVal + "条数据");
}else {
System.out.println("更新操作执行失败");
}
}
- 编写测试类+调试查看数据库(删除用户)
@Test
public void deleteUserTest(){
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
UserDao userDao = (UserDao) applicationContext.getBean("userDao");
int retVal = userDao.deleteUser(1);
if(retVal>0){
System.out.println("成功删除了" + retVal + "条数据");
}else {
System.out.println("删除操作执行失败");
}
}
4.3 query() 查询数据
- 修改UserDao
public interface UserDao {
public int addUser(User user);
public int updateUser(User user);
public int deleteUser(int id);
public User findUserById(int id);
public List<User> findAllUser();
}
- 修改UserDaoImpl
@Override
public User findUserById(int id) {
String sql = "select * from user where id=?";
RowMapper<User> rowMapper = new BeanPropertyRowMapper<User>(User.class);
return this.jdbcTemplate.queryForObject(sql,rowMapper);
}
@Override
public List<User> findAllUser() {
String sql = "select * from user";
RowMapper<User> rowMapper = new BeanPropertyRowMapper<User>(User.class);
return this.jdbcTemplate.queryForObject(sql,rowMapper,id);
}
- 编写测试类
@Test
public void findUserById(){
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
UserDao userDao = (UserDao) applicationContext.getBean("userDao");
User user = userDao.findUserById(2);
System.out.println(user);
}
@Test
public void findAllUser(){
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
UserDao userDao = (UserDao) applicationContext.getBean("userDao");
List<User> userList = userDao.findAllUser();
for (User user:userList){
System.out.println(user);
}
}
- 测试
先用之前的addUserTest
测试函数,往数据库添加几个User.
添加成功后开始测试刚写的两个测试方法.
0x05 Spring JdbcTemplat的解析
大致翻译下文档写的介绍.
JdbcTemplate是JDBC核心包的中心类.它简化了JDBC的使用,避免了常见错误.它能够执行JDBC核心工作流,使程序代码能够通过提供SQL语句来获取结果.这个类通过ResultSets执行SQL查询/更新/初始化迭代器,截取JDBC异常并把它们转译成org.springframework.dao 包中定义的通用的、信息更丰富的异常层次结构.
参考资料
- MySQL 安装 | 菜鸟教程 (runoob.com)
- MySQL8.0.21安装教程(Windows系统) - 华为云 (huaweicloud.com)
- mysql5.7初始化密码报错 ERROR 1820 (HY000): You must reset your password using ALTER USER statement before - 开始认识 - 博客园 (cnblogs.com)
- java - MySQLNonTransientConnectionException: Client does not support authentication protocol requested by server; consider upgrading MySQL client - Stack Overflow
- java - Could not load JDBC driver class [com.mysql.jdbc.Driver] - Stack Overflow
- 使用Maven构建spring JdbcTemplate项目_1号帅比的博客-CSDN博客_jdbctemplate maven
- Spring - applicationContext.xml cannot be opened because it does not exist - Stack Overflow
- 138 张图带你 MySQL 入门 (juejin.cn)
- Spring入门(十五):使用Spring JDBC操作数据库 (juejin.cn)
- JDBC 框架概述 - Spring 教程 - 极客学院Wiki (jikexueyuan.com)
- 使用JDBC - 廖雪峰的官方网站 (liaoxuefeng.com)
- JDBC简介 - 廖雪峰的官方网站 (liaoxuefeng.com)