1 回答

TA貢獻(xiàn)1820條經(jīng)驗(yàn) 獲得超9個(gè)贊
代碼不會(huì)關(guān)閉,因此會(huì)泄漏資源。有點(diǎn)丑陋的 Try-With-Resources 語法確保關(guān)閉連接、語句和結(jié)果集,即使在返回/異常時(shí)也是如此。
可以使用Optional明確表明圖像是否在表中找到。
Optional.of還保證數(shù)據(jù)庫中的字段不能包含 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) {
還有一點(diǎn)還是要說明的是,我個(gè)人并不經(jīng)常使用ResultSet.getBytes,但還是有的getInputStream。取決于圖像大小和創(chuàng)建代碼。
添加回答
舉報(bào)