1. pom.xml配置
<dependency>
<groupId>org.springframework.boot
</groupId>
<artifactId>spring-boot-starter-jdbc
</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot
</groupId>
<artifactId>spring-boot-starter-web
</artifactId>
</dependency>
<dependency>
<groupId>mysql
</groupId>
<artifactId>mysql-connector-java
</artifactId>
<scope>runtime
</scope>
</dependency>
2. yml文件配置数据源
spring:
datasource:
url: jdbc
:mysql
://localhost
:3306/test
?serverTimezone=UTC
&useUnicode=true
&characterEncoding=utf
-8
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
3. 编写controller,操作数据库
@RestController
public class UserController {
@Autowired
private JdbcTemplate jdbcTemplate
;
@GetMapping("/getAllUser")
public List
<Map
<String,Object>> getAllUser(){
String sql
= "select * from user";
List
<Map
<String,Object>> res
= jdbcTemplate
.queryForList(sql
);
return res
;
}
@GetMapping("/addUser")
public String
addUser(){
String sql
= "insert into user values('10','小明','123')";
jdbcTemplate
.update(sql
);
return "add成功";
}
@GetMapping("/updateUser/{id}")
public String
updateUser(@PathVariable("id") int id
){
String sql
= "update user set name=?,password=? where id="+id
;
Object
[] objects
= new Object[2];
objects
[0]="lize1";
objects
[1]="123456";
jdbcTemplate
.update(sql
,objects
);
return "update成功";
}
@GetMapping("/deleteUser/{id}")
public String
deleteUser(@PathVariable("id") int id
){
String sql
= "delete from user where id="+id
;
jdbcTemplate
.update(sql
);
return "delete成功";
}
}
转载请注明原文地址:https://tech.qufami.com/read-2151.html