Sping JdbcTemplate

打印 上一主题 下一主题

主题 918|帖子 918|积分 2754

Sping JdbcTemplate

JdbcTemplate概述

JdbcTemplate 是 Spring JDBC 核心包(core)中的核心类,它可以通过配置文件、注解、Java 配置类等形式获取数据库的相关信息,实现了对 JDBC 开发过程中的驱动加载、连接的开启和关闭、SQL 语句的创建与执行、异常处理、事务处理、数据类型转换等操作的封装。我们只要对其传入SQL 语句和必要的参数即可轻松进行 JDBC 编程。
开发步骤


  • 导入spring-jdbc和spring-tx坐标
    1. <dependency>
    2.   <groupId>org.springframework</groupId>
    3.   <artifactId>spring-jdbc</artifactId>
    4.   <version>5.3.6</version>
    5. </dependency>
    6. <dependency>
    7.   <groupId>org.springframework</groupId>
    8.   <artifactId>spring-tx</artifactId>
    9.   <version>5.3.6</version>
    10. </dependency>
    复制代码
  • 创建数据库表和实体对象
  • 创建jdbctemplate对象
  • 执行数据库操作
    1.     public  void  test1() throws PropertyVetoException {
    2. //        创建一个数据源对象
    3.         ComboPooledDataSource dataSource = new ComboPooledDataSource();
    4.         dataSource.setDriverClass("com.mysql.jdbc.Driver");
    5.         dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/test");
    6.         dataSource.setUser("root");
    7.         dataSource.setPassword("123456");
    8. //                创建jdbctemplate对象
    9.         JdbcTemplate jdbcTemplate = new JdbcTemplate();
    10. //        设置数据源对象,知道数据库在哪里
    11.         jdbcTemplate.setDataSource(dataSource);
    12. //        执行操作
    13.         jdbcTemplate.update("insert into account values (?,?)","tom",5000);
    14.         
    15.         
    16.     }
    复制代码
利用spring产生jdbctemplate对象(创建数据源bean实例再将其注入jdbctemplate实例,然后通过spring容器获得)

让后为了解耦更加彻底,还可以把相关配置信息抽出为单独配置文件,以前写过很多次了不再多说
常用操作

修改(包括更新、删除、插入):
  1. jdbcTemplate.update("insert into account values (?,?)","tom",5000);
复制代码
查询:
  1. //         查询多个对象
  2. //        Account是你要封装的实类的泛型
  3.         List<Account> query = jdbcTemplate.query("select * from account", new BeanPropertyRowMapper<Account>(Account.class));
复制代码
  1. //        查询一个对象
  2.         jdbcTemplate.queryForObject("select * from account where name = ?",new BeanPropertyRowMapper<Account>(Account),"tom")
复制代码
  1. //        聚合查询
  2.         Long aLong = jdbcTemplate.queryForObject("select count(*) from account ", Long.class);
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

乌市泽哥

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表