用MySQL客户端,新建测试数据库
客户端:MySQL Workbench
根pom添加依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency>
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<String> getMySQLKey() { String sql = "SELECT name FROM test_table"; List<String> 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