首页 > 技术文章 > SpringBoot整合JDBC

malongfeistudy 2022-03-24 23:59 原文

SpringBoot整合JDBC

1、新建一个 jdbccontroller.java

@RestController
public class JDBCController {

    @Autowired
    JdbcTemplate jdbcTemplate;

    //查询数据库的所有信息
    //没有实体类,数据库中的东西,怎么获取? Map
    @GetMapping("/userList")
    public List<Map<String,Object>> userList(){
        String sql="select * from user";
        return jdbcTemplate.queryForList(sql);
    }

    @GetMapping("/add")
    public ModelAndView addUser(){
        String sql="insert into mybatis.user(id, name, pwd) VALUE (10,'malongfei','123456')";
        jdbcTemplate.update(sql);
        System.out.println("添加成功!");
        return new ModelAndView("redirect:/userList");
    }

    @GetMapping("/update/{id}")
    public ModelAndView updateUser(@PathVariable("id") int id){
        String sql="update mybatis.user set name=?,pwd=? where id="+id;
        Object[] obj= new Object[]{"小米米","fdhsajkhfd"};
        jdbcTemplate.update(sql, obj);
        System.out.println("更新成功!");
        return new ModelAndView("redirect:/userList");
    }

    @GetMapping("/delete/{id}")
    public ModelAndView deleteUser(@PathVariable("id") int id){
        String sql="delete from user where id=?";
        jdbcTemplate.update(sql, id);
        System.out.println("刪除成功!");
        return new ModelAndView("redirect:/userList");
    }
}

分别实现了增删改查!

2、数据库如:

3、application.yml配置文件:

spring:
  datasource:
    username: root
    password: 123456
    url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&useUncode=true&characterEncoding=utf-8
    driver-class-name: com.mysql.cj.jdbc.Driver

推荐阅读