使用 JDBC操作数据库
- 创建一个springboot 项目,选择JDBC 依赖配置
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
- 配置数据库信息
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# 这里使用的是MySql 8.0.15 数据库,需要加时区,保证自己的数据库db_jdbc 存在。
spring.datasource.url=jdbc:mysql://localhost:3306/db_jdbc?\
useSSL=true&useUnicode=true&characterEncoding=utf8&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=666666
3.创建实体类
package com.zdy.springboot.pojo;
/**
* @author deyou
* @create 2020-03-27 11:53 PM
*/
public class User {
private int id;
private String user_name;
private String user_password;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUser_name() {
return user_name;
}
public void setUser_name(String user_name) {
this.user_name = user_name;
}
public String getUser_password() {
return user_password;
}
public void setUser_password(String user_password) {
this.user_password = user_password;
}
public User() {
}
public User(int id, String user_name, String user_password) {
this.id = id;
this.user_name = user_name;
this.user_password = user_password;
}
}
- 创建Controller 类
package com.zdy.springboot.controller;
import com.zdy.springboot.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* @author deyou
* @create 2020-03-27 11:59 PM
*/
@RestController
public class UserController {
@Autowired
private JdbcTemplate jdbcTemplate;
/*访问地址: http://localhost:8080/createTable*/
@GetMapping("createTable")
public String createTable(){
String sql = "CREATE TABLE `user` (\n" +
" `id` int(11) NOT NULL AUTO_INCREMENT,\n" +
" `user_name` varchar(255) DEFAULT NULL,\n" +
" `user_password` varchar(255) DEFAULT NULL,\n" +
" PRIMARY KEY (`id`)\n" +
") ENGINE=InnoDB DEFAULT CHARSET=utf8;";
jdbcTemplate.execute(sql);
return "创建User表成功";
}
/*访问地址: http://localhost:8080/saveUser*/
//保存数据
@GetMapping("saveUser")
public String saveUser(String username,String password){
String sql = "INSERT INTO `user` (`user_name`, `user_password`) VALUES (?, ?)";
int rows = jdbcTemplate.update(sql,username,password);
return "执行成功,影响数据"+rows+"行";
}
//修改方法
//http://localhost:8080/updateUserPassword?id=1&password=10000000
//RestFul 风格:http://localhost:8080/updateUserPassword/1/123456789
@GetMapping("updateUserPassword/{ID}/{pwd}")
public String updateUserPassword(@PathVariable("ID") int id, @PathVariable("pwd") String password){
String sql = "Update user set user_password = " +
"? where id=? ";
int rows = jdbcTemplate.update(sql, password, id);
return ("执行修改成功,影响"+rows+"行");
}
//删除方法
//http://localhost:8080/deleteUserById/2
@GetMapping("deleteUserById/{id}")
public String deleteUserById(@PathVariable("id") int id){
String sql = "delete from user where id = ?";
int rows = jdbcTemplate.update(sql, id);
return ("执行删除成功,影响"+rows+"行");
}
//通过名字查询
//http://localhost:8080/queryUserbyUserName?username=deyou
@GetMapping("queryUserbyUserName")
public List<User> queryUserbyUserName(String username){
String sql = "select * from user where user_name = ?";
List<User> list = jdbcTemplate.query(sql, new Object[]{username}, new BeanPropertyRowMapper<>(User.class));
return list;
}
//通过Id查询
//http://localhost:8080/queryUserbyId?id=deyou
@GetMapping("queryUserbyId")
public User queryUserbyId(int id){
String sql = "select * from user where id = ?";
/*添加一个查询不到数据的异常处理*/
User user = null;
try {
user=jdbcTemplate.queryForObject(sql, new Object[]{id}, new BeanPropertyRowMapper<>(User.class));
}catch (EmptyResultDataAccessException e){
return null;
}
return user;
}
//批处理添加数据
//http://localhost:8080/batchSaveUser?num=10
@GetMapping("batchSaveUser")
public String batchSaveUser(int num){
String sql = "INSERT INTO `user` (`user_name`, `user_password`) VALUES (?, ?)";
List<Object[]> userList = new ArrayList<>();
for (int i = 0; i < num ; i++) {
String[] arr= new String[2];
arr[0] = "zhangsan"+i;
arr[1] = "password"+i;
userList.add(arr);
}
int[] ints = jdbcTemplate.batchUpdate(sql, (userList));
System.out.println(ints);
return "执行成功";
}
//通过map 查询对象
//http://localhost:8080/getMapUserById/10
@GetMapping("getMapUserById/{id}")
public Map getMapUserById(@PathVariable("id") int id){
String sql = "select * from user where id =?";
Map map =null;
/*添加一个查询不到数据的异常处理*/
try{
map = jdbcTemplate.queryForMap(sql, id);
}catch (EmptyResultDataAccessException e){
return null;
}
return map;
}
}