新建 spring
项目时,导入mysql
驱动,如下
配置数据库连接文件(在application.yml
中配置)
spring:
datasource:
username: root
password: 123456
url: jdbc:mysql://localhost:3306/study?useUnicode=true&characterEncoding=utf-8
driver-class-name: com.mysql.jdbc.Driver
表中数据如下:
新建controller
测试
- 查
@GetMapping("/select")
public List<Map<String,Object>> selectUser(){
String sql="select * from student";
List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql);
return maps;
}
- 增
@GetMapping("add")
public boolean addUser(){
String sql="insert into student(name,age) values('小李',22)";
jdbcTemplate.update(sql);
return true;
}
- 改
@GetMapping("update/{id}")
public boolean updateUser(@PathVariable("id") int id){
String sql="update student set name='lan' where id="+id;
jdbcTemplate.update(sql);
return true;
}
4. 删
@GetMapping("/delete/{id}")
public boolean deletedUser(@PathVariable("id") int id){
String sql="delete from student where id=?";
jdbcTemplate.update(sql,id);
return true;
}