Spring提供的jdbc框架之JDBCTemplate

本文介绍了Spring框架中的JdbcTemplate,它如何封装JDBC以提高易用性,以及如何配置Durid连接池。涵盖了JdbcTemplate的基本使用方法,如执行SQL(DDL、DML、DQL),数据查询、更新操作和数据映射到对象或Map的API示例。
摘要由CSDN通过智能技术生成

1、介绍
JdbcTemplate是Spring对JDBC的封装,目的是使JDBC更加易于使用。JdbcTemplate是Spring的一部分。JdbcTemplate处理了资源的建立和释放。他帮助我们避免一些常见的错误,比如忘了总要关闭连接。他运行核心的JDBC工作流,如Statement的建立和执行,而我们只需要提供SQL语句和提取结果。
Spring源码地址:

https://github.com/spring-projects/spring-framework

在JdbcTemplate中执行SQL语句的方法大致分为3类:

  • execute:可以执行所有SQL语句,一般用于执行DDL语句。
  • update:用于执行INSERT、UPDATE、DELETE等DML语句。
  • queryXxx:用于DQL数据查询语句。

2、使用方式
(1)导入依赖

spring-beans-4.1.2.RELEASE.jar spring-core-4.1.2.RELEASE.jar
spring-jdbc-4.1.2.RELEASE.jar spring-tx-4.1.2.RELEASE.jar
commons.logging-1.1.1.jar

注意:若是使用springboot,则直接引入Spring-boot-starter-jdbc依赖即可

此处以durid连接池

duridxxx.jar

(2)编写数据源/连接池配置

driverClassName=com.mysql.jdbc.Driver
url=jdbc\:mysql\://127.0.0.1\:3306/test
username=root
password=xxxxx
initialSize=5
maxActive=10
maxWait=3000
minIdle=3
validationQuery:SELECT 1
testWhileIdle:true
testOnBorrow:false
testOnReturn:false

(3)编写编写加载数据源工具类

public class JdbcTemplateUtil {
    /**
     * 定义成员变量DataSource
     */
    private static DataSource ds;
    static{
        try {
            Properties pro =new Properties();
            InputStream is=JdbcTemplateUtil.class.getClassLoader().getResourceAsStream("com/customization/sanxin/druid.properties");
            pro.load(is);
            ds= DruidDataSourceFactory.createDataSource(pro);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //获取连接
    public static Connection getConnection() throws SQLException{
        return ds.getConnection();


    }
    //释放资源
    public static void close(Statement stmt,Connection conn){
        if(stmt!=null){
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(conn!=null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    public static void close(PreparedStatement pstmt,Connection conn){


        if(pstmt!=null){
            try {
                pstmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(conn!=null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    public static void close(ResultSet rs,Statement stmt,Connection conn){
        if(rs!=null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(stmt!=null){
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(conn!=null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    /*获取连接池方法(获取数据源)*/
    public static DataSource getDataSource(){
        return ds;


    }
}

(4)编写程序
3、JdbcTemplate常用Api
(1)query()
用于查询数据封装成对象

public class test {
    public static void main(String[] args) throws SQLException {
        JdbcTemplate jdbcTemplate = new JdbcTemplate(JdbcTemplateUtil.getDataSource());
        List <book>list = jdbcTemplate.query("select * from book ",new BeanPropertyRowMapper<book>(book.class));
        for (book b:list) {
            System.out.println(b);
        }
    }
}

(2)queryForObject()
查询一条数据封装成一个对象

public class test {
    public static void main(String[] args) throws SQLException {
        JdbcTemplate jdbcTemplate = new JdbcTemplate(JdbcTemplateUtil.getDataSource());
        book b = (book) jdbcTemplate.queryForObject("select * from book where name ='java'", new BeanPropertyRowMapper<book>(book.class));
        System.out.println(b);
    }
}

(3)update()
用于数据的插入、删除、修改

public static void test02() throws Exception {
        JdbcTemplate jdbcTemplate = new JdbcTemplate(DataSourceUtils.getDataSource());
        String sql = "UPDATE product SET pname=?, price=? WHERE pid=?;";
        int i = jdbcTemplate.update(sql, "XVIII", 18888, 10);
        System.out.println("影响的行数: " + i);
    }

(4)queryForMap()
用于查询数据封装成map

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);
}
  • 4
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值