• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

mysqltinyint(1)对应java的boolean问题和解决方案jdbc查询

武飞扬头像
秋叶随风起
帮助1

首先展示下我的问题,可以看见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类型)

学新通

由于数据库不能轻易改动,所以我选择了法二,下面看下查询结果,成功解决
学新通

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhfjgkef
系列文章
更多 icon
同类精品
更多 icon
继续加载