1、导入 maven 依赖
数据库相关的启动器官方文档
<!-- jdbc -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!-- mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
2、yml 配置文件
# com.mysql.jdbc.Driver 是 MySQL5 版本的驱动
# com.mysql。cj.jdbc.Driver 是 MySQL8 版本的驱动
# ?serverTimezone=UTC 设置时区
spring:
datasource:
username: username
password: password
url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8
driver-class-name: com.mysql.cj.jdbc.Driver
# 默认数据源是 class com.zaxxer.hikari.HikariDataSource,可以不写 type
type: com.alibaba.druid.pool.DruidDataSource
3、测试代码
@RestController
public class JDBCController {
@Autowired
JdbcTemplate jdbcTemplate;
@RequestMapping("/userlist")
public List<Map<String, Object>> userList(){
String sql = "SELECT * FROM user";
List<Map<String, Object>> userList = jdbcTemplate.queryForList(sql);
return userList;
}
@RequestMapping("updateUser/{id}-{name}-{age}")
public String updateUser(@PathVariable("id") int id, @PathVariable("name") String name, @PathVariable("age") int age){
try {
String sql = "UPDATE USER SET name = ?, age = ? WHERE 1 = 1 AND id = " + id;
Object[] objects = {name, age};
jdbcTemplate.update(sql, objects);
return "update-ok";
} catch (DataAccessException e) {
e.printStackTrace();
return "update-no";
}
}
}