Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store and retrieve images in Postgresql using Java [closed]

I am new to Java programming, I am searching for Java code to store images in PostgreSQL and to retrieve the image.

In PostgreSQL I have used Bytea Data-type. the image was stored. but when I retrieve I am getting NULL. I cant get the image.

Any example for this or any other suggestion on this would be helpful.

like image 796
MAHI Avatar asked Feb 28 '13 03:02

MAHI


1 Answers

chapter 7 of the postgresql jdbc documentation deals with storing binary data and uses an image (*.gif file) an an example. you might want to read it.

inserting an image into the db (from the link above)

File file = new File("myimage.gif");
FileInputStream fis = new FileInputStream(file);
PreparedStatement ps = conn.prepareStatement("INSERT INTO images VALUES (?, ?)");
ps.setString(1, file.getName());
ps.setBinaryStream(2, fis, (int)file.length());
ps.executeUpdate();
ps.close();
fis.close();

reading an image from the db (also from the link above)

// Get the Large Object Manager to perform operations with
LargeObjectManager lobj = ((org.postgresql.PGConnection)conn).getLargeObjectAPI();

PreparedStatement ps = conn.prepareStatement("SELECT imgoid FROM imageslo WHERE imgname = ?");
ps.setString(1, "myimage.gif");
ResultSet rs = ps.executeQuery();
while (rs.next()) {
    // Open the large object for reading
    int oid = rs.getInt(1);
    LargeObject obj = lobj.open(oid, LargeObjectManager.READ);

    // Read the data
    byte buf[] = new byte[obj.size()];
    obj.read(buf, 0, obj.size());
    // Do something with the data read here

    // Close the object
    obj.close();
}
rs.close();
ps.close();
like image 71
radai Avatar answered Nov 13 '22 10:11

radai