Spring Boot 入门(六)使用MySQL


用MySQL客户端,新建测试数据库

客户端:MySQL Workbench

根pom添加依赖


    org.springframework.boot
    spring-boot-starter-jdbc


    mysql
    mysql-connector-java
    runtime
package com.example.demo.controller;

import org.springframework.beans.factory.annotation.Autowired;import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class HelloWorldController {
    @Autowired
    JdbcTemplate jdbcTemplate;

    @RequestMapping("/hello")
    public String index() {
        return "Hello World";
    }

    @RequestMapping("/setMySQLKey")
    public String setMySQLKey(String val) {
        String sql = "INSERT INTO test_table(`name`) VALUES(?)";
        jdbcTemplate.update(sql, new Object[]{val});
        return "true";
    }

    @RequestMapping("/getMySQLKey")
    public List getMySQLKey() {
        String sql = "SELECT name FROM test_table";
        List nameList = jdbcTemplate.queryForList(sql, String.class);
        return nameList;
    }
}

application.properties添加配置

# 数据库设置
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://xx.xx.xxx.xx:3306/test_db?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8 
spring.datasource.username=root
spring.datasource.password=xxxxxx

添加数据:http://localhost:8080/setMySQLKey?val=%E5%BC%A0%E4%B8%89

查询数据:http://localhost:8080/getMySQLKey