Hi,
I found this post in a forum. What do you think about it? :)
Christophe
----------------------------------------------------------------------------
----
I have used JDBC extensively with pg 7.2.4, but I have not used the bytea
type to send data to/from a java application.
I found the most relevant data in the 7.4 documentation, and it says 7.2 is
the first version that supports bytea through the JDBC driver.
Version 7.2 was the first release of the JDBC driver that supports the bytea
data type. The introduction of this functionality in 7.2 has introduced a
change in behavior as compared to previous releases. Since 7.2, the methods
getBytes(), setBytes(), getBinaryStream(), and setBinaryStream() operate on
the bytea data type. In 7.1 and earlier, these methods operated on the oid
data type associated with Large Objects. It is possible to revert the driver
back to the old 7.1 behavior by setting the property compatible on the
Connection object to the value 7.1.
To use the bytea data type you should simply use the getBytes(), setBytes(),
getBinaryStream(), or setBinaryStream() methods.
and perhaps exactly what you may be looking for
To insert an image, you would use:
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, file.length());
ps.executeUpdate();
ps.close();
fis.close();
Here, setBinaryStream() transfers a set number of bytes from a stream into
the column of type bytea. This also could have been done using the
setBytes() method if the contents of the image was already in a byte[].
Retrieving an image is even easier. (We use PreparedStatement here, but the
Statement class can equally be used.)
PreparedStatement ps = con.prepareStatement("SELECT img FROM images WHERE
imgname = ?");
ps.setString(1, "myimage.gif");
ResultSet rs = ps.executeQuery();
if (rs != null) {
while (rs.next()) {
byte[] imgBytes = rs.getBytes(1);
// use the data in some way here
}
rs.close();
}
ps.close();
Here the binary data was retrieved as an byte[]. You could have used a
InputStream object instead.