SpringBoot 之 整合JDBC使用

导入相关依赖: # pom.xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </depe...

导入相关依赖:

# pom.xml

<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>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>

配置数据库连接信息:

# src/main/resources/application.yml

spring:
  datasource:
    username: root
    password: 123456
    url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC
    # driver-class-name: com.mysql.jdbc.Driver # 已过时
    driver-class-name: com.mysql.cj.jdbc.Driver

测试连接:

@SpringBootTest
public class SpringbootDataApplicationTests {
    @Autowired
    DataSource dataSource;

    @Test
    public void contextLoads() throws SQLException {
    	// 查看默认数据源
        System.out.println(dataSource.getClass());
        
    	// 查看链接
        Connection connection = dataSource.getConnection();
        System.out.println(connection);
        connection.close();
    }
}

简单使用示例:

# src/main/java/com/wu/controller/JdbcController.java

@RestController
public class JdbcController {
    @Autowired
    JdbcTemplate jdbcTemplate;
 
    @GetMapping("/users")
    public List<Map<String, Object>> index() {
        String sql = "select * from user";
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
        return list;
    }
 
    @PostMapping("/users")
    public int store() {
        String sql = "insert into user(id,name) values (1,'小明')";
        return jdbcTemplate.update(sql);
    }
 
    @GetMapping("/users/{id}")
    public Map<String, Object> show(@PathVariable("id") int id) {
        String sql = "select * from user where id=" + id;
        Map<String, Object> map = jdbcTemplate.queryForObject(sql);
        return map;
    }
 
    @PutMapping("/users/{id}")
    public int update(@PathVariable("id") int id) {
        String sql = "update user set name=? where id=" + id;
        Object[] objects = new Object[1];
        objects[0] = "小花";
        return jdbcTemplate.update(sql, objects);
    }
 
    @DeleteMapping("/users/{id}")
    public int destroy(@PathVariable("id") int id) {
        String sql = "delete from user where id=?";
        return jdbcTemplate.update(sql, id);
    }
}
  • 发表于 2020-05-06 08:46
  • 阅读 ( 144 )
  • 分类:网络文章

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除