java中使用jdbcTemplate的query方法举例与总结

本文介绍了Java中使用Spring JdbcTemplate进行数据查询的多种方法,包括queryForInt、queryForObject、queryForMap和queryForList等,展示了如何通过这些方法高效地从数据库获取所需数据。

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

Java中使用JdbcTemplate进行查询时,可以使用queryForXXX()等方法

1、jdbcTemplate.queryForInt() 和 jdbcTemplate.queryForLong()

//查询数据记录的条数,返回一个int(数据范围较小)或者一个Long(数据范围较大)类型

String todayCountTopicsSql="SELECT count(*) FROM mcp_forum_post";

Integer todayCount=jdbcTemplate.queryForInt(todayCountTopicsSql);

也可以:Long todayCount=jdbcTemplate.queryForLong(todayCountTopicsSql);


2、jdbcTemplate.queryForObject() 

本质上和queryForInt()相同,返回都是单行单列一个数据,例如传回一个String对象: 
String userAccountSql="select account from scpn_user where user_id="+userAccountId;
String userAccount=(String)jdbcTemplate.queryForObject(userAccountSql, java.lang.String.class);


3、jdbcTemplate.queryForMap()

查询一行数据,即一条记录,一条记录包含多个字段, 使用返回的列做key。

  1. String userAccountSql="select account,create_time from scpn_user where user_id="+userAccountId;  
  2. Map userAccountMap=(Map)jdbcTemplate.queryForMap(userAccountSql);  
  3. String userAccount= (String)userAccountMap.get("account");    //取出数据库中char类型的数据转换为String  
  4. String createTime= (String)userAccountMap.get("create_time").toString();  //取出数据库中datetime类型的数据转换为String   

4、 jdbcTemplate.queryForList():返回Map的集合List(它包含多条记录), 用列名做key, 每一个map代表一条数据库记录,需要使用循环来输出每一条记录,如果想在结果集中加入一个字段,也可以采用如下的put方法。

 

  1. String all="SELECT * FROM mcp_forum_post";  
  2.   List scpnPostList = jdbcTemplate.queryForList(all);  
  3. if (scpnPostList!=null) {  
  4.    for (int i = 0; i < scpnPostList.size(); i++) {  
  5.   Long userAccountId = (Long) scpnPostList.get(i).get("user_id");  
  6.    Long lastmodUser = (Long) scpnPostList.get(i).get("lastmod_user");  
  7.  if (lastmodUser!=null) {  
  8.    String lastmodUserSql="select account from scpn_user where user_id="+lastmodUser;  
  9.    String lastmodUserAccount=(String)jdbcTemplate.queryForObject(lastmodUserSql, java.lang.String.class);  
  10.    scpnPostList.get(i).put("lastmodUserAccount", lastmodUserAccount);//可以在结果集中插入一个字段  
  11.   }  
  12.   
  13.    }  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值