数据库:mysql
框架:struts2+spring+mybatis
项目中很多地方用到count(*)来查询数据量,今天在写一个新的小功能时想要吧数据处理做的简单些
原来的sql:
select count(1) AS count1
from ke_table1 a
where a.user_id=#{userId}
union all
select count(1) AS count2
from ke_table2 b
where b.user_id=#{userId}1234567
返回结果是int型
用list来接收返回值:
List<Integer> rst = manageService.searchCnt();// 获取总数
int totalCnt=rst.get(0)+rst.get(1)//总数12
这样处理没有任何错误,今天在处理另一个相似功能时,决定换一个思路
sql调整为:
select count(a.id) AS count1,count(b.id) AS count2
from ke_table1 a inner join ke_table2 b on a.user_id=b.user_id
where a.user_id=#{userId}123
查询结果:
采用map来接收返回结果
Map<String, Object> rst = manageService.searchCnt();// 获取总数
int count1=(Integer)rst.get("count1");
int count2=(Integer)rst.get("count2");
count=count1+count2;//总数1234
程序运行到int count1=rst.get("count1");
时报错
ERROR 2017-07-26 09:54:09,171 java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.Integer
因此,可见sql语句count(列名)
返回的并不是int类型,而是long型值,最后调整代码
String count1 = rst.get("count1").toString();
int counta = Integer.parseInt(count1);
String count2 = rst.get("count2").toString();
int countb = Integer.parseInt(count2);
int count = counta+countb;//总数12345
通过!
标签:count,int,long,rst,sql,count1,count2,id From: https://www.cnblogs.com/javaxubo/p/16655067.html