You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

rs.Next()调用异常:MySQL图片GUI展示跳行问题求助

解决MySQL ResultSet跳过行的问题

兄弟,你的问题根源太明显了——你在image2()方法里不小心调用了两次rs.next(),这直接导致每次读取数据时都会跳过一行!

咱们拆解下你的代码问题:

  1. 第一次if (rs.next())已经把ResultSet的指针移动到了当前有效行,你在这里正确获取了Blob和ID;
  2. 但紧接着你加了一行System.out.println(rs.next());,这行代码又把指针往前移动了一行!等于每次调用image2(),你实际跳过了一行数据,自然会出现图片和ID都跳着显示的情况。

而且这行System.out.println(rs.next());完全是多余的调试代码,删掉它就能解决问题。

修改后的image2()方法如下:

public Pair<Integer,Image> image2()throws SQLException { 
    int id; 
    System.out.println("I am in Image"); 
    try { 
        System.out.println(rs); 
        boolean anyResults = false; 
        if (rs.next()) { 
            anyResults = true; 
            Blob blob = rs.getBlob("image"); 
            id = rs.getInt("id"); 
            System.out.println(id); 
            System.out.println(blob); 
            System.out.println(blob.length()); 
            InputStream in = blob.getBinaryStream(1, blob.length()); 
            // 删掉下面这行多余的rs.next()调用
            // System.out.println(rs.next()); 
            System.out.println(in); 
            BufferedImage image = ImageIO.read(in); 
            System.out.println(image); 
            Image image1 = SwingFXUtils.toFXImage(image,null); 
            return new Pair<>(id, image1); 
        } else if (!anyResults) { 
            JOptionPane.showMessageDialog(null, "Not Found"); 
        } 
        System.out.println("reached here"); 
    } catch (Exception e) { 
        e.printStackTrace(); 
    } 
    return null; 
}

另外补充一句:你提到if(rs.next())和while(rs.next())逻辑一致,其实这里你是单次获取一行数据,用if完全没问题,但一定要记住ResultSet的指针是单向移动的,每调用一次next()就会前进一行,所以在读取当前行数据的过程中,绝对不能额外调用next(),否则就会跳过数据。

内容的提问来源于stack exchange,提问作者Zaid

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 06:46:02