1 回答

TA貢獻1820條經驗 獲得超9個贊
代碼不會關閉,因此會泄漏資源。有點丑陋的 Try-With-Resources 語法確保關閉連接、語句和結果集,即使在返回/異常時也是如此。
可以使用Optional明確表明圖像是否在表中找到。
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。取決于圖像大小和創建代碼。
添加回答
舉報