JdbcTemplate基本使用

JdbcTemplate基本使用

​ JDBC已经能够满足大部分用户最基本的需求,但是在使用JDBC时,必须自己来管理数据库资源如:获取PreparedStatement,设置SQL语句参数,关闭连接等步骤。

​ JdbcTemplate是Spring对JDBC的封装,目的是使JDBC更加易于使用。JdbcTemplate是Spring的一部分。JdbcTemplate处理了资源的建立和释放。他帮助我们避免一些常见的错误,比如忘了总要关闭连接。他运行核心的JDBC工作流,如Statement的建立和执行,而我们只需要提供SQL语句和提取结果。
Spring源码地址:https://github.com/spring-projects/spring-framework
在JdbcTemplate中执行SQL语句的方法大致分为3类:

  1. execute:可以执行所有SQL语句,一般用于执行DDL语句。
  2. update:用于执行INSERTUPDATEDELETE等DML语句。
  3. queryXxx:用于DQL数据查询语句。
JdbcTemplate配置连接池

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

  1. public JdbcTemplate(DataSource dataSource)
    创建JdbcTemplate对象,方便执行SQL语句
    
  2. public void execute(final String sql)
    execute可以执行所有SQL语句,因为没有返回值,一般用于执行DDL语句。
    
JdbcTemplate使用步骤
  1. 准备DruidDataSource连接池
  2. 导入依赖的jar包
    • 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
    • com.springsource.org.apache.commons.logging-1.1.1.jar
  3. 创建JdbcTemplate对象,传入Druid连接池
  4. 调用executeupdatequeryXxx等方法
案例代码
public class Demo04 {
	public static void main(String[] args) {
		// 创建表的SQL语句
		String sql = "CREATE TABLE product("
				+ "pid INT PRIMARY KEY AUTO_INCREMENT,"
				+ "pname VARCHAR(20),"
				+ "price DOUBLE"
				+ ");";
				
		JdbcTemplate jdbcTemplate = new JdbcTemplate(DataSourceUtils.getDataSource());
		jdbcTemplate.execute(sql);
	}
}

JdbcTemplate实现增删改

API介绍

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

  1. public int update(final String sql)
    用于执行`INSERT`、`UPDATE`、`DELETE`等DML语句。
    
使用步骤

1.创建JdbcTemplate对象
2.编写SQL语句
3.使用JdbcTemplate对象的update方法进行增删改

案例代码
public class Demo05 {
	public static void main(String[] args) throws Exception {
//		test01();
//		test02();
//		test03();
	}
	
	// JDBCTemplate添加数据
	public static void test01() throws Exception {
		JdbcTemplate jdbcTemplate = new JdbcTemplate(DataSourceUtils.getDataSource());
		
		String sql = "INSERT INTO product VALUES (NULL, ?, ?);";
		
		jdbcTemplate.update(sql, "iPhone3GS", 3333);
		jdbcTemplate.update(sql, "iPhone4", 5000);
		jdbcTemplate.update(sql, "iPhone4S", 5001);
		jdbcTemplate.update(sql, "iPhone5", 5555);
		jdbcTemplate.update(sql, "iPhone5C", 3888);
		jdbcTemplate.update(sql, "iPhone5S", 5666);
		jdbcTemplate.update(sql, "iPhone6", 6666);
		jdbcTemplate.update(sql, "iPhone6S", 7000);
		jdbcTemplate.update(sql, "iPhone6SP", 7777);
		jdbcTemplate.update(sql, "iPhoneX", 8888);
	}
	
	// JDBCTemplate修改数据
	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);
	}

	// JDBCTemplate删除数据
	public static void test03() throws Exception {
		JdbcTemplate jdbcTemplate = new JdbcTemplate(DataSourceUtils.getDataSource());
		String sql = "DELETE FROM product WHERE pid=?;";
		int i = jdbcTemplate.update(sql, 7);
		System.out.println("影响的行数: " + i);
	}
}

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. 输出结果
案例代码
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类型的数据。
使用步骤
  1. 创建JdbcTemplate对象
  2. 编写查询的SQL语句
  3. 使用JdbcTemplate对象的queryForList方法
  4. 处理结果
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);
   }
}
  1. 使用JdbcTemplate对象的query方法,并传入RowMapper匿名内部类
  2. 在匿名内部类中将结果集中的一行记录转成一个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接口
使用步骤
  1. 定义Product类
  2. 创建JdbcTemplate对象
  3. 编写查询的SQL语句
  4. 使用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));

	for (Product product : list) {
		System.out.println(product);
	}
}
  • 230
    点赞
  • 800
    收藏
    觉得还不错? 一键收藏
  • 25
    评论
Spring的JdbcTemplate是Spring框架对JDBC进行封装的一个工具类,旨在使JDBC更加易于使用JdbcTemplate处理了资源的建立和释放,帮助我们避免一些常见的错误,比如忘记关闭连接。使用JdbcTemplate可以简化数据库操作的代码量,并提供了一些便捷的方法来执行数据库查询、更新等操作。 使用JdbcTemplate的步骤如下: 1. 引入相关的jar包,包括druid-1.1.9.jar、spring-jdbc-5.2.6.RELEASE.jar、spring-orm-5.2.6.RELEASE.jar和spring-tx-5.2.6.RELEASE.jar。这些jar包提供了JdbcTemplate的实现和相关依赖。 2. 在Spring的配置文件中添加数据库连接的配置,包括数据库的URL、用户名、密码和驱动类名等信息。这可以通过配置一个DataSource对象来实现。 3. 配置JdbcTemplate对象,将DataSource对象注入到JdbcTemplate中。可以通过在Spring的配置文件中定义一个JdbcTemplate的bean,并设置其dataSource属性为前面配置的DataSource对象。 4. 创建service和dao对象,将JdbcTemplate对象注入到dao中。在dao层的代码中,可以通过在dao类中定义一个JdbcTemplate的成员变量,并在dao类的构造方法或通过依赖注入的方式将JdbcTemplate对象注入进来。这样,就可以在dao中使用JdbcTemplate来执行数据库操作了。 通过上述步骤,我们就可以在Spring项目中使用JdbcTemplate来进行数据库操作了。JdbcTemplate提供了一系列的方法,如查询、更新、批处理等,可以根据具体的需求选择合适的方法来使用使用JdbcTemplate可以简化数据库操作的代码,并提高开发效率。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [Spring之jdbcTemplate使用](https://blog.csdn.net/ABestRookie/article/details/127232689)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] - *2* [JdbcTemplate基本使用](https://download.csdn.net/download/weixin_38606076/14939780)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] - *3* [Spring之JdbcTemplate使用](https://blog.csdn.net/qq_38628046/article/details/108111318)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值