java-开发笔记-JdbcTemplate-常用语法

本文详细展示了如何利用Spring的JdbcTemplate进行数据库的基本操作,包括插入(Insert)、查询(Select)等。通过示例代码,演示了更新记录、获取单个整数值、查询Map集合、List集合以及使用RowMapper和BeanPropertyRowMapper返回自定义对象的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.进行增删改的操作 

JdbcTemplate jdbcTemplate = new JdbcTemplate(DataSourceUtils.getDataSource());
String sql = "INSERT INTO product VALUES (NULL, ?, ?);";
jdbcTemplate.update(sql, "iPhone3GS", 3333);

2.进行查询的操作

2.1 返回一个int整数

String sql = "SELECT pid FROM product WHERE price=18888;";
JdbcTemplate jdbcTemplate = new JdbcTemplate(DataSourceUtils.getDataSource());
int forInt = jdbcTemplate.queryForInt(sql);

2.2 返回一个Map集合 

String sql = "SELECT * FROM product WHERE pid=?;";
JdbcTemplate jdbcTemplate = new JdbcTemplate(DataSourceUtils.getDataSource());
Map<String, Object> map = jdbcTemplate.queryForMap(sql, 6);

2.3 返回一个List集合

String sql = "SELECT * FROM product WHERE pid<?;";
JdbcTemplate jdbcTemplate = new JdbcTemplate(DataSourceUtils.getDataSource());
List<Map<String, Object>> list = jdbcTemplate.queryForList(sql, 8);

2.4 RowMapper返回自定义对象

JdbcTemplate jdbcTemplate = new JdbcTemplate(DataSourceUtils.getDataSource());
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;
      }
   });

2.5 BeanPropertyRowMapper返回自定义对象

JdbcTemplate jdbcTemplate = new JdbcTemplate(DataSourceUtils.getDataSource());
// 查询数据的SQL语句
String sql = "SELECT * FROM product;";
List<Product> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Product.class));

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值