SpringBoot 使用 JdbcTemplate 执行sql

参考文章: https://www.cnblogs.com/caoyc/p/5630622.html
原文链接: https://blog.csdn.net/weixin_40001125/article/details/88538576

JdbcTemplate简介

Spring对数据库的操作在jdbc上面做了深层次的封装,使用spring的注入功能,可以把DataSource注册到JdbcTemplate之中。

JdbcTemplate主要提供以下四类方法:

execute 方法:可以用于执行任何SQL语句,一般用于执行DDL语句; update 方法及batchUpdate方法:update方法用于执行新增、修改、删除等语句;batchUpdate方法用于执行批处理相关语句; query 方法及queryForXXX方法:用于执行查询相关语句; call 方法:用于执行存储过程、函数相关语句。

1.引入maven

<!-- springboot 整合 jdbcTemplate jar包 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

2.填写配置

spring:
  application:
    name: restful-api
  datasource:
    name: bdp_spider
    url: jdbc:mysql://localhost:3306/bdp_spider?useUnicode=true&characterEncoding=UTF8
    username: root
    password: pwd
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.jdbc.Driver
    filters: stat
    maxActive: 20
    initialSize: 1
    maxWait: 60000
    minIdle: 1
    timeBetweenEvictionRunsMillis: 60000
    minEvictableIdleTimeMillis: 300000
    validationQuery: select 'x'
    testWhileIdle: true
    testOnBorrow: false
    testOnReturn: false
    poolPreparedStatements: true
    maxOpenPreparedStatements: 20

3. 配置DataSourceConfig

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.core.JdbcTemplate;
import javax.sql.DataSource;
 * @Author goujunqiang
 * @Date 2019/10/15
@Configuration
public class DataSourceConfig {
    @Bean(name = "baseDataSource")
    @ConfigurationProperties(prefix = "spring.datasource") // application.properteis中对应属性的前缀
    @Primary
    public DataSource dataSourceBase() {
        return new DruidDataSource();
    @Bean(name = "resourceJdbcTemplate")
    public JdbcTemplate inditeJdbcTemplate(@Qualifier("baseDataSource") DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    @Bean(name = "scannerCodeDataSource")
    @ConfigurationProperties(prefix = "spring.datasource-white-bucket")
    public DataSource scannerDataSource() {
        return new DruidDataSource();
    @Bean(name = "scannerJdbcTemplate")
    public JdbcTemplate scannerCodeJdbcTemplate(@Qualifier("scannerCodeDataSource") DataSource dataSource) {
        return new JdbcTemplate(dataSource);

4.执行实例

package cn.example.restfulapi.sys.task;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Map;
 * @author Mr.Hao
 * @date 2020-04-29
@Component
public class JdbcTest {
    @Resource(name = "resourceJdbcTemplate")
    JdbcTemplate JdbcTemplate;
    @PostConstruct
    public void start(){
        String sql = "SELECT * FROM `snapshot_info` limit 1;";
        Map<String, Object> stringObjectMap = JdbcTemplate.queryForMap(sql);
        System.out.println("=============查询返回一个map==================");
        System.out.println(stringObjectMap);
/*        System.out.println("=============插入数据==================");
        String insertSql = "INSERT INTO snapshot_info VALUES (NULL, ?, ?);";
        int  x = JdbcTemplate.update(insertSql, 7);*/
        System.out.println("===============删除数据================");
        String DeleteSql = "DELETE FROM snapshot_info WHERE id=?;";
        int i = JdbcTemplate.update(DeleteSql, 9944);
        System.out.println("影响的行数: " + i);
        System.out.println("===============更新数据================");
        String updateSql = "UPDATE snapshot_info SET task_id=?  WHERE id=?;";
        int z = JdbcTemplate.update(updateSql, 11, 9943);
        System.out.println("影响的行数: " + z);

6.查询api详述

JdbcTemplate查询-queryForInt返回一个int整数

org.springframework.jdbc.core.JdbcTemplate类方便执行SQL语句

API介绍

public int queryForInt(String sql)
执行查询语句,返回一个int类型的值。
  • 1.创建JdbcTemplate对象
  • 2.编写查询的SQL语句
  • 3.使用JdbcTemplate对象的queryForInt方法
  • 4.输出结果
  • // queryForInt返回一个整数
    public static void test01() throws Exception {
       // String sql = "SELECT COUNT(*) FROM product;";
       String sql = "SELECT pid FROM product WHERE price=18888;";
       JdbcTemplate jdbcTemplate = new JdbcTemplate(DataSourceUtils.getDataSource());
       int forInt = jdbcTemplate.queryForInt(sql);
       System.out.println(forInt);
    

    JdbcTemplate查询-queryForLong返回一个long整数

    org.springframework.jdbc.core.JdbcTemplate类方便执行SQL语句

    API介绍

    public long queryForLong(String sql)
    执行查询语句,返回一个long类型的数据。
    
  • 1.创建JdbcTemplate对象
  • 2.编写查询的SQL语句
  • 3.使用JdbcTemplate对象的queryForLong方法
  • 4.输出结果
  • // queryForLong  返回一个long类型整数
    public static void test02() throws Exception {
       String sql = "SELECT COUNT(*) FROM product;";
       // String sql = "SELECT pid FROM product WHERE price=18888;";
       JdbcTemplate jdbcTemplate = new JdbcTemplate(DataSourceUtils.getDataSource());
       long forLong = jdbcTemplate.queryForLong(sql);
       System.out.println(forLong);
    

    JdbcTemplate查询-queryForObject返回String

    org.springframework.jdbc.core.JdbcTemplate类方便执行SQL语句

    API介绍

    public <T> T queryForObject(String sql, Class<T> requiredType)
    执行查询语句,返回一个指定类型的数据。
    
  • 1.创建JdbcTemplate对象
  • 2.编写查询的SQL语句
  • 3.使用JdbcTemplate对象的queryForObject方法,并传入> - 4.需要返回的数据的类型
  • 5.输出结果
    public static void test03() throws Exception {
       String sql = "SELECT pname FROM product WHERE price=7777;";
       JdbcTemplate jdbcTemplate = new JdbcTemplate(DataSourceUtils.getDataSource());
       String str = jdbcTemplate.queryForObject(sql, String.class);
       System.out.println(str);
    

    JdbcTemplate查询-queryForMap返回一个Map集合

    API介绍

    public Map<String, Object> queryForMap(String sql)
    执行查询语句,将一条记录放到一个Map中。
    
  • 1.创建JdbcTemplate对象
  • 2.编写查询的SQL语句
  • 3.使用JdbcTemplate对象的queryForMap方法
  • 4.处理结果
  • public static void test04() throws Exception {
       String sql = "SELECT * FROM product WHERE pid=?;";
       JdbcTemplate jdbcTemplate = new JdbcTemplate(DataSourceUtils.getDataSource());
       Map<String, Object> map = jdbcTemplate.queryForMap(sql, 6);
       System.out.println(map);
    

    JdbcTemplate查询-queryForList返回一个List集合

    目标: 能够掌握JdbcTemplate中queryForList方法的使用

    org.springframework.jdbc.core.JdbcTemplate类方便执行SQL语句

    API介绍
    public List<Map<String, Object>> queryForList(String sql)
    执行查询语句,返回一个List集合,List中存放的是Map类型的数据。
    
  • 创建JdbcTemplate对象
  • 编写查询的SQL语句
  • 使用JdbcTemplate对象的queryForList方法
  • public static void test05() throws Exception {
       String sql = "SELECT * FROM product WHERE pid<?;";
       JdbcTemplate jdbcTemplate = new JdbcTemplate(DataSourceUtils.getDataSource());
       List<Map<String, Object>> list = jdbcTemplate.queryForList(sql, 8);
       for (Map<String, Object> map : list) {
          System.out.println(map);
    

    queryForList方法的作用?将返回的一条记录保存在Map集合中,多条记录对应多个Map,多个Map存储到List集合中

    JdbcTemplate查询-RowMapper返回自定义对象

    org.springframework.jdbc.core.JdbcTemplate类方便执行SQL语句

    API介绍

    public <T> List<T> query(String sql, RowMapper<T> rowMapper)
    执行查询语句,返回一个List集合,List中存放的是RowMapper指定类型的数据。
    
  • 1.定义Product类
  • 2.创建JdbcTemplate对象
  • 3.编写查询的SQL语句
  • 4.使用JdbcTemplate对象的query方法,并传入RowMapper匿名内部类
  • 5.在匿名内部类中将结果集中的一行记录转成一个Product对象
    // query使用rowMap做映射返回一个对象
    public static void test06() throws Exception {
        JdbcTemplate jdbcTemplate = new JdbcTemplate(DataSourceUtils.getDataSource());
       // 查询数据的SQL语句
       String sql = "SELECT * FROM product;";
       List<Product> query = jdbcTemplate.query(sql, new RowMapper<Product>() {
          @Override
          public Product mapRow(ResultSet arg0, int arg1) throws SQLException {
             Product p = new Product();
             p.setPid(arg0.getInt("pid"));
             p.setPname(arg0.getString("pname"));
             p.setPrice(arg0.getDouble("price"));
             return p;
       for (Product product : query) {
          System.out.println(product);
    

    JdbcTemplate查询-BeanPropertyRowMapper返回自定义对象

    org.springframework.jdbc.core.JdbcTemplate类方便执行SQL语句

    API介绍

    public <T> List<T> query(String sql, RowMapper<T> rowMapper)
    执行查询语句,返回一个List集合,List中存放的是RowMapper指定类型的数据。
    
    public class BeanPropertyRowMapper<T> implements RowMapper<T>
    BeanPropertyRowMapper类实现了RowMapper接口
    
  • 定义Product类
  • 创建JdbcTemplate对象
  • 编写查询的SQL语句
  • 使用JdbcTemplate对象的query方法,并传入BeanPropertyRowMapper对象
  • // query使用BeanPropertyRowMapper做映射返回对象
    public static void test07() throws Exception {
        JdbcTemplate jdbcTemplate = new JdbcTemplate(DataSourceUtils.getDataSource());
        // 查询数据的SQL语句
        String sql = "SELECT * FROM product;";
        List<Product> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Product.class));