使用Java在Postgresql中存储和检索图像
问题描述:
我是Java编程的新手,我正在寻找Java代码以在PostgreSQL中存储图像并检索图像。使用Java在Postgresql中存储和检索图像
在PostgreSQL中,我已经使用了Bytea数据类型。图像被存储。但是当我检索时,我得到NULL。我无法得到图像。
对此或任何其他建议的任何示例都会有所帮助。
答
chapter 7 postgresql jdbc文档处理存储二进制数据和使用图像(* .gif文件)的一个例子。你可能想阅读它。
插入图像插入分贝(从上面的链接)
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();
从分贝(也从上面的链接)读取图像
// 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();
bytea的java等效数据类型是字节。它是否正确 ! – MAHI 2013-02-28 03:48:56
您需要显示一些代码才能获得帮助! – 2013-02-28 03:49:31
我衷心推荐使用谷歌这种信息寻求... – ppeterka 2013-02-28 09:11:04