sql count id 返回long型数据

数据库: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

通过!

posted @   哩个啷个波  阅读(770)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
点击右上角即可分享
微信分享提示