Updating JLabel via SetIcon from bytea data type in postgres

后端 未结 1 1014
失恋的感觉
失恋的感觉 2020-12-21 18:24

I am retrieving gif images from Wolfram|Alpha. In an effort to minimize queries I want to store those images and only query W|A when the data is changed, so I am storing th

相关标签:
1条回答
  • 2020-12-21 18:53

    I don't have a installation of PostgreSQL available, but I think you should be writing/reading the image format and not the BufferedImage data.

    For example, writing might look something like...

    Connection con = ...;
    BufferedImage img = ...;
    try (PreparedStatement stmt = con.prepareStatement("insert into tableofimages (image) values (?)")) {
        try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
            ImageIO.write(img, "png", baos);
            try (ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray())) {
                stmt.setBinaryStream(1, bais);
                int rows = stmt.executeUpdate();
                System.out.println(rows + " rows updated");
            }
        }
    } catch (SQLException | IOException exp) {
        exp.printStackTrace();
    }
    

    And reading might look something like...

    Connection con = ...;
    try (PreparedStatement stmt = con.prepareStatement("select image from tableofimages")) {
        try (ResultSet rs = stmt.executeQuery()) {
            while (rs.next()) {
                try (InputStream is = rs.getBinaryStream(1)) {
                    BufferedImage img = ImageIO.read(is);
                }
            }
        }
    } catch (SQLException | IOException exp) {
        exp.printStackTrace();
    }
    
    0 讨论(0)
提交回复
热议问题