为什么 ResultSet 不 return 来自 MySQL 的数据
Why ResultSet don't return the data from MySQL
我想从 MySQL 数据库中获取图像并显示在 JLabel
中,但是当我执行查询并尝试从 ResultSet
中获取字节时returns 一个空数组。
我测试了连接,它工作正常,测试了查询,它也工作。
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();
}
代码没有关闭,因此泄漏了资源。有点丑陋的 Try-With-Resources 语法确保关闭连接、语句和结果集,即使在 returning/exception.
上也是如此
可以使用 Optional 明确表示图像是否在 table 中找到。
Optional.of
还保证数据库中的字段不得包含 SQL NULL 值。
Optional<byte[]> loadImageFromDatabase(String imageM) throws SQLException {
String sql = "select img_imagem from imagem where serial_imagem = ?";
try (Connection conn = getConnection();
PreparedStatement pst = conn.prepareStatement(sql)) {
pst.setString(1, imageM);
try (ResultSet rs = pst.executeQuery()) {
if (rs.next()) {
return Optional.of(rs.getBytes(1)); // ofNullable
} else {
return Optional.empty();
}
}
}
}
用法:
try {
Optional<byte[]> img = loadImageFromDatabase(jtextField1.getText().trim());
img.ifPresent(image -> {
...
});
} catch (SQLException e) {
还有一点要说的是,我个人并不经常使用ResultSet.getBytes
,而是getInputStream
。取决于图像大小和创建代码。
我想从 MySQL 数据库中获取图像并显示在 JLabel
中,但是当我执行查询并尝试从 ResultSet
中获取字节时returns 一个空数组。
我测试了连接,它工作正常,测试了查询,它也工作。
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();
}
代码没有关闭,因此泄漏了资源。有点丑陋的 Try-With-Resources 语法确保关闭连接、语句和结果集,即使在 returning/exception.
上也是如此可以使用 Optional 明确表示图像是否在 table 中找到。
Optional.of
还保证数据库中的字段不得包含 SQL NULL 值。
Optional<byte[]> loadImageFromDatabase(String imageM) throws SQLException {
String sql = "select img_imagem from imagem where serial_imagem = ?";
try (Connection conn = getConnection();
PreparedStatement pst = conn.prepareStatement(sql)) {
pst.setString(1, imageM);
try (ResultSet rs = pst.executeQuery()) {
if (rs.next()) {
return Optional.of(rs.getBytes(1)); // ofNullable
} else {
return Optional.empty();
}
}
}
}
用法:
try {
Optional<byte[]> img = loadImageFromDatabase(jtextField1.getText().trim());
img.ifPresent(image -> {
...
});
} catch (SQLException e) {
还有一点要说的是,我个人并不经常使用ResultSet.getBytes
,而是getInputStream
。取决于图像大小和创建代码。