前言
Spring 框架对 JDBC 进行封装,使用 JdbcTemplate 方便实现对数据库操作
一、在maven中添加相关依赖
<!--spring jdbc Spring 持久化层支持jar包-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>6.0.2</version>
</dependency>
<!-- MySQL驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.30</version>
</dependency>
<!-- 数据源 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.15</version>
</dependency>
二、配置数据库连接文件
jdbc.user=root
jdbc.password=123456
jdbc.url=jdbc:mysql://localhost:3306/spring?characterEncoding=utf8&useSSL=false
jdbc.driver=com.mysql.cj.jdbc.Driver
三、spring配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 导入外部属性文件 -->
<context:property-placeholder location="classpath:jdbc.properties" />
<!-- 配置数据源 -->
<bean id="druidDataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="url" value="${jdbc.url}"/>
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="username" value="${jdbc.user}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!-- 配置 JdbcTemplate -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<!-- 装配数据源 -->
<property name="dataSource" ref="druidDataSource"/>
</bean>
</beans>
三、CURD
@SpringJUnitConfig(locations = "classpath:beans.xml")//利用Junit5创建Spring容器
public class jdbcTemplateTest {
@Autowired//利用注解完成属性注入
private JdbcTemplate jdbcTemplate;
//添加、修改、删除
@Test
public void testUpdate(){
//1、增
// String sql = "INSERT INTO t_emp VALUES(NULL,?,?,?)";
// Object[] params = {"Musk",52,"男"};
// int rows = jdbcTemplate.update(sql, params);
// System.out.println("受影响的行数:" + rows);
//2、 改
// String sql = "update t_emp set age=? where id=?";
// Object[] params = {18,1};
// int rows = jdbcTemplate.update(sql, params);
// System.out.println("受影响的行数:" + rows);
// }
//3、删
// String sql = "delete from t_emp where id=?";
// Object[] params = {3};
// int rows = jdbcTemplate.update(sql, params);
// System.out.println("受影响的行数:" + rows);
}
//查询
@Test
public void testSelect(){
//返回对象
// String sql = "select * from t_emp where id = ?";
// Emp emp = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(Emp.class), 1);
// System.out.println(emp);
//返回List集合
// String sql = "select * from t_emp";
// List<Emp> empList = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Emp.class));
// System.out.println(empList);
//返回单个值
String sql = "select count(*) from t_emp ";
Integer rows = jdbcTemplate.queryForObject(sql, Integer.class);
System.out.println(rows);
}
}