JDBCcontroller
package com.jdbcstudy.controller;
import org.springframework.beans.factory.annotation.Autowired;
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.List;
import java.util.Map;
@RestController
public class JDBCController {
@Autowired
JdbcTemplate jdbcTemplate;
//查询数据库的所有信息
@GetMapping("/userlist")
public List<Map<String,Object>> studentList(){
String sql = "select * from student";
List<Map<String,Object>> list_maps = jdbcTemplate.queryForList(sql);
return list_maps;
}
//新增数据
@GetMapping("/adduser")
public String addUser(){
String sql ="insert into studentsql.student(id,name,age) values (6,'xiaoming','55')";
jdbcTemplate.update(sql);
return "add ok";
}
//修改
@GetMapping("/updateUser/{id}")
public String updateUser(@PathVariable("id") int id){
String sql ="update studentsql.student set name=?,age=? where id="+id;
//封装
Object[] objects = new Object[2];
objects[0] = "小明";
objects[1] = "188";
jdbcTemplate.update(sql,objects);
return "updata ok";
}
//删除
@GetMapping("/deleteUser/{id}")
public String deleteUser(@PathVariable("id") int id){
String sql ="delete from studentsql.student where id = ?";
jdbcTemplate.update(sql,id);
return "delete ok";
}
}
application.yml
spring:
datasource:
username: root
password: 123
url: jdbc:mysql://localhost:3306/studentsql?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
driver-class-name: com.mysql.cj.jdbc.Driver
数据库测试
package com.jdbcstudy;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
@SpringBootTest
class SpringbootJdbcDataApplicationTests {
@Autowired
DataSource dataSource;
@Test
void contextLoads() throws SQLException {
//查看一下默认的数据源:class com.zaxxer.hikari.HikariDataSource
System.out.println(dataSource.getClass());
//获得数据库连接
Connection connection = dataSource.getConnection();
System.out.println(connection);
//xxxx Template:springboot已经配置好的模板bean,拿来即用
//数据库关闭
connection.close();
}
}