Search code examples
javasqlimageswingjlabel

Why ResultSet don't return the data from MySQL


I'm tying to get an image from MySQL database and show in a JLabel, but when I execute the query and try to get the bytes from the ResultSet it returns an empty array.

I tested the connection, and it is working, tested the query and its also working.

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();
}   

Solution

  • The code does not close and thus leaks resources. The somewhat ugly Try-With-Resources syntax ensures closing connection, statement and result set, even on returning/exception.

    One could make explicit with Optional whether the image was found in the table or not.

    Optional.of also guarantees that the field in the database must not contain an SQL NULL value.

    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();
               }
           }
        }
    }
    

    Usage:

        try {
            Optional<byte[]> img = loadImageFromDatabase(jtextField1.getText().trim());
            img.ifPresent(image -> {
                    ...
                });
        } catch (SQLException e) {
    

    There is still to remark that I personally do not often use ResultSet.getBytes, but rather getInputStream. Depends on the image size and creation code.