新建一个springboot项目
打开New Project > 选择Spring initializr 然后next
需要导入webmvc导入依赖
<!--web依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
新建一个application.yml配置文件
spring:
datasource:
username: root
password: 123456
# 假如市区报错了,就增加一个时区的配置就ok了 serverTimezone=UTC
url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
driver-class-name: com.mysql.jdbc.Driver
数据库
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(20) auto_increment,
`name` varchar(30) DEFAULT NULL,
`pwd` varchar(30) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `user` VALUES (‘1‘, ‘李倩‘, ‘123123‘);
INSERT INTO `user` VALUES (‘2‘, ‘张三‘, ‘123456‘);
INSERT INTO `user` VALUES (‘3‘, ‘李四‘, ‘123456‘);
INSERT INTO `user` VALUES (‘4‘, ‘赵柳‘, ‘1234556‘);
INSERT INTO `user` VALUES (‘6‘, ‘libai‘, ‘123456‘);
INSERT INTO `user` VALUES (‘7‘, ‘lisi‘, ‘123123‘);
INSERT INTO `user` VALUES (‘8‘, ‘聊吧‘, ‘123123‘);
增删改查
@RestController的使用
https://www.cnblogs.com/rzkwz/p/12936806.html
@RestController
public class JDBCController {
@Autowired
JdbcTemplate jdbcTemplate;
//查询数据库的所有信息
//没有实体类,数据库中的东西,怎么获取 Map
@GetMapping("/userList")
public List<Map<String,Object>> userList(){
String sql="select * from user";
List<Map<String, Object>> list_maps = jdbcTemplate.queryForList(sql);
return list_maps;
}
@GetMapping("addUser")
public String addUser(){
String sql = "insert into user(id,name,pwd) values(10,‘小妞‘,‘123123‘)";
jdbcTemplate.update(sql);
return "update-ok";
}
@GetMapping("/updateUser/{id}")
public String updateUser(@PathVariable("id") int id){
String sql = "update user set name=?,pwd=? where id="+id;
//封装
Object[] objects = new Object[2];
objects[0] ="小明";
objects[1] ="11111";
jdbcTemplate.update(sql,objects);
return "update-ok";
}
@GetMapping("/delUser/{id}")
public String delUser(@PathVariable("id") int id){
String sql = "delete from user where id = ?";
jdbcTemplate.update(sql,id);
return "update-ok";
}
}
启动主入口
测试
@SpringBootApplication