SpringBoot从0到0.7——第三天

SpringBoot从0到0.7——第三天

今天学习整合JDBC,连接数据库的增删改查,写出来容易,理解原理读懂代码才是主要的。

首先创建项目,勾选上一下模块

 

在application.yml添加

spring:
  datasource:
    username: root
    password: 123456789
    url: jdbc:mysql://localhost:3306/spring?useUnicode=true&characterEncoding=utf-8
    driver-class-name: com.mysql.cj.jdbc.Driver

 

 

 调取数据库数据,先创建一个controller包,在包里面创建一个JDBCController类

package com.mantou.demo3.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Map;


@RestController
public class JDBCController {
    @Autowired
    JdbcTemplate jdbcTemplate;

    @RequestMapping("/select")
    public List all(){
        String sql = "select * from admin";
        return jdbcTemplate.queryForList(sql);
    }

    @RequestMapping("/insert")
    public String  insert(){
        String sql = "insert into admin(username,password) values ('test','test123456')";
        jdbcTemplate.update(sql);
        return "插入成功";
    }

    @RequestMapping("/update")
    public String update(){
        String sql = "update admin set password =? where username='test'";
        jdbcTemplate.update(sql,"admin");
        return "更新成功";
    }
    //在URL上来指定删除username的目标
    @RequestMapping("/delete/{username}")
    public String delete(@PathVariable("username") String username){
        String sql = "delete from admin where username=?";
        jdbcTemplate.update(sql,username);
        return "删除成功";
    }

}

 访问localhost:8080/insert,再次访问localhost:8080/select查询

 

 再来执行一下删除localhost:8080/delete/test,之后再次查询

 

 

 

 

 

 

 

posted @ 2022-04-09 17:07  mt0u  阅读(44)  评论(0编辑  收藏  举报