首先展示下我的问题,可以看见id为66,64,63对应的month_age分别为1,1,0,但是数据库中这三条记录对应的month_age应该是11,5,0
造成这个错误的原因是我们在设计数据库时,将month_age这个字段的类型设为tinyint(1),而tinyint(1)对应java中的boolean类型,0对应false,非0对应true
然后由于我代码是这样写的
public DataList getChildVisitAndExaminList(Integer personId, Integer... createAgencyId) throws SQLException { ArrayList<Object> condition = new ArrayList<>(); condition.add(personId); Connection connection = JDBCUtils.getConnection(); String sqlStr = "select id,month_age,visit_date,doctor_id,doctor,next_date,create_agency,create_agencyid from" + " tbl_children_visit where is_delete != 1 and person_id = ?"; if (createAgencyId.length > 0) { sqlStr += " and create_agencyid = ?"; condition.add(createAgencyId[0]); } sqlStr += " order by id desc"; PreparedStatement ps = connection.prepareStatement(sqlStr); for (int i = 0; i < condition.size(); i++) { ps.setObject(i + 1, condition.get(i)); } ResultSet rs = ps.executeQuery(); ResultSetMetaData md = rs.getMetaData(); int columnCount = md.getColumnCount(); Map<String, Object> rowData = new HashMap<>(); List<ChildrenListRes> list = new ArrayList<>(); while (rs.next()) { for (int i = 1; i <= columnCount; i++) { if (md.getColumnLabel(i).equals("visit_date") || md.getColumnLabel(i).equals("next_date")) { rowData.put(md.getColumnLabel(i),TimeUtil.timeStamp2Date(rs.getObject(i,Long.class))); } else { rowData.put(md.getColumnLabel(i), rs.getObject(i)); } } String jsonStr = JSONObject.toJSONString(rowData); ChildrenListRes childrenListRes = JSONObject.parseObject(jsonStr, ChildrenListRes.class); list.add(childrenListRes); } // 拼接photo ChildrenDao.getChildrenPhotoPath(list); JDBCUtils.release(connection, ps, rs); return new DataList(list); }
rs.getObject(i)由于定义的是object类型,他这里拿到false就会转成0,true就会转成1
解决方案:
法一:改数据库字段类型
将tinyint(1)改为tinyint(4),mysql的tinyint默认为tinyint(4)
关于tinyint与java中类型对应关系可参考此链接
法二:修改代码,多添加一个判断,如下(这种情况针对数据库字段里面没用bit类型)
由于数据库不能轻易改动,所以我选择了法二,下面看下查询结果,成功解决
来源地址:https://blog.csdn.net/qq_34252060/article/details/130255142