JDBCTemplate-介绍

JDBCTemplate介绍

spring框架对JDBC的简单封装 提供了一个JDBCTemplate对象简化JDBC的开发

步骤

1.导入依赖

  <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.3.18</version>
        </dependency>

2.创建JDBCTemplate对象 依赖于数据源DataSource

jdbcTemplate template = new jdbcTemplate(ds);

3.调用jdbcTemplate的方法来完成CRUD的操作

update():执行DML语句 增 删 改语句
queryForMap():查询结果将结果集封装为map集合
queryForList():查询结果将结果封装为list集合
query():查询结果 将结果封装为javaBean对象
queryForobject:查询结果 将结果封装为对象

代码

复制代码
 public static void main(String[] args) {
        //1.创建JDBCTemplate对象
        JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
//2.调用方法
        String sql="update account set balance = 500 where id=?";
        int count=template1.update(sql,2);

        System.out.println(count);
    }
复制代码

JDBCUtils类

复制代码
public class JDBCUtils {
    //定义成员变量 DataSource
    private static DataSource ds;

    static {
        try {
            //1.加载配置文件
            Properties pro = new Properties();
            pro.load(JdkXmlUtils.class.getClassLoader().getResourceAsStream("druid.properties"));
            //2.获取DataSource
            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(ResultSet rs, Statement stmt, Connection conn) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }

        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
    /**
     * 获取连接方法
     */
    public static DataSource getDataSource(){
        return ds;
    }

}
复制代码
posted @   baimingze  阅读(47)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
点击右上角即可分享
微信分享提示