为什么 ResultSet 不从 MySQL 返回数据

我想从 MySQL 数据库获取图像并显示在 a 中JLabel,但是当我执行查询并尝试从 a 中获取字节时,ResultSet它返回一个空数组。


我测试了连接,它正在工作,测试了查询,它也工作了。


try {

    conn = getConnection();

    pst = conn.prepareStatement("select * from imagem where serial_imagem = 123658");

    rs = pst.executeQuery()


    if (rs.next()) {

        image = rs.getBytes("img_imagem");

    }

}catch (Exception e) {

    e.printStackTrace();

}  


aluckdog
浏览 104回答 1
1回答

慕妹3146593

代码不会关闭,因此会泄漏资源。有点丑陋的 Try-With-Resources 语法确保关闭连接、语句和结果集,即使在返回/异常时也是如此。可以使用Optional明确表明图像是否在表中找到。Optional.of还保证数据库中的字段不能包含 SQL NULL 值。Optional<byte[]> loadImageFromDatabase(String imageM) throws SQLException {&nbsp; &nbsp;String sql = "select img_imagem from imagem where serial_imagem = ?";&nbsp; &nbsp;try (Connection conn = getConnection();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;PreparedStatement pst = conn.prepareStatement(sql)) {&nbsp; &nbsp; &nbsp; &nbsp;pst.setString(1, imageM);&nbsp; &nbsp; &nbsp; &nbsp;try (ResultSet rs = pst.executeQuery()) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;if (rs.next()) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;return Optional.of(rs.getBytes(1)); // ofNullable&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;} else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;return Optional.empty();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; }}用法:&nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; Optional<byte[]> img = loadImageFromDatabase(jtextField1.getText().trim());&nbsp; &nbsp; &nbsp; &nbsp; img.ifPresent(image -> {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ...&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; } catch (SQLException e) {还有一点还是要说明的是,我个人并不经常使用ResultSet.getBytes,但还是有的getInputStream。取决于图像大小和创建代码。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java