使用Java在Postgresql中存储和检索图像

5

我是Java编程的新手,我想要找到Java代码来将图像存储在PostgreSQL中并检索出图像。

在PostgreSQL中,我使用了Bytea数据类型来存储图像。图像已经被存储了,但是当我检索时,我得到了NULL。我无法获取图像。

如果有任何关于此的示例或其他建议,都会很有帮助。


Java中bytea的等价数据类型是byte。这个说法正确吗? - MAHI
你需要展示一些代码才能得到帮助! - James Drinkard
我衷心推荐使用谷歌搜索这类信息... - ppeterka
我知道它完美地工作,就按照你说的去做。 - Audrius Meškauskas
2个回答

13

第七章的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();

这个链接也非常有用:http://zetcode.com/db/postgresqljavatutorial/ - MAHI
谢谢你提供这个链接,redai。我一直在寻找它。 - Luffy

-1

浏览一下Java数据库连接 API,这里有一个连接到Postgres数据库的示例。如果有任何疑问,请跟进!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接