一:准備數據庫表結構
create table user0( id int unsigned primary key , name varchar(32) not null default '', pwd varchar(32) not null default '') engine=myisam charset utf8; create table user1( id int unsigned primary key , name varchar(32) not null default '', pwd varchar(32) not null default '') engine=myisam charset utf8; create table user2( id int unsigned primary key , name varchar(32) not null default '', pwd varchar(32) not null default '') engine=myisam charset utf8; create table uuid( id int unsigned primary key auto_increment)engine=myisam charset utf8;
二:准備依賴
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.38</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
三:配置文件
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/mydata
spring.datasource.username=root
spring.datasource.password=123
四:業務代碼
package com.yjc.service; 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; @RestController public class register { @Autowired JdbcTemplate jdbcTemplate; @RequestMapping("/register") public String register(String name,String pwd){ //往uuid表中添加一條空記錄,主鍵自增 String insertSql="INSERT INTO uuid VALUES (NULL);"; jdbcTemplate.update(insertSql); //獲取最后一次添加數據的主鍵 Long aLong = jdbcTemplate.queryForObject("select last_insert_id()", Long.class); //取余,看看存到哪張表里 String table="user"+aLong%3; //插入到該去的表中 String insertUserSql = "INSERT INTO " + table + " VALUES ('" + aLong + "','" + name + "','" + pwd + "');"; jdbcTemplate.update(insertUserSql); return "success"; } @RequestMapping("/get") public String get(Long id){ //去拿張表里取數據 String table ="user"+id%3; String sql = "select name from " + table + " where id="+id; String name = jdbcTemplate.queryForObject(sql, String.class); return name; } }
五:測試
啟動項目請求,模擬用戶注冊情況
http://localhost:8080/register?name=123&pwd=123
http://localhost:8080/get?id=8
