pom.xml
<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>
application.yaml
spring:
datasource:
username: root
password: 12345678
url: jdbc:mysql://localhost:3306/javaweb?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
driver-class-name: com.mysql.cj.jdbc.Driver
package com.faa.lpfproject01;
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 Lpfproject01ApplicationTests {
@Autowired
DataSource dataSource;
@Test
void contextLoads() throws SQLException {
System.out.println(dataSource.getClass());
Connection connection = dataSource.getConnection() ;
System.out.println(connection);
connection.close();
}
}
package com.faa.lpfproject01.controller;
import com.faa.lpfproject01.mapper.UserMapper;
import com.faa.lpfproject01.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Map;
@RestController
public class HelloController {
@Autowired
JdbcTemplate jdbcTemplate;
@RequestMapping("/hello")
public String hello(){
return "hello word";
}
@RequestMapping("/getList")
public List<Map<String ,Object>> getList(){
String sql = "select * from javaweb.t_user";
List<Map<String ,Object>> maplist = jdbcTemplate.queryForList(sql);
return maplist;
}
@RequestMapping("/addUser")
public List<Map<String ,Object>> addUser(){
String sql = "insert into t_user(id,name) values(15,'哇啊啊')";
jdbcTemplate.update(sql);
String sql2 = "select * from javaweb.t_user";
List<Map<String ,Object>> maplist = jdbcTemplate.queryForList(sql2);
return maplist;
}
@RequestMapping("/updataById/{id}")
public String updataUser(@PathVariable("id") int id){
String sql = "update t_user set name='噗哈哈' where id=?";
Object[] options = new Object[1];
options[0] = id;
jdbcTemplate.update(sql,options);
return "ok";
}
@RequestMapping("/deleteById/{id}")
public String delectById(@PathVariable("id") int id){
String sql = "delete from t_user where id=?";
Object[] options = new Object[1];
options[0] = id;
jdbcTemplate.update(sql,options);
return "ok";
}
}