【问题标题】:Store and retrieve images in Postgresql using Java [closed]使用 Java 在 Postgresql 中存储和检索图像 [关闭]
【发布时间】:2013-02-28 03:47:59
【问题描述】:

我是 Java 编程新手,我正在搜索 Java 代码以在 PostgreSQL 中存储图像并检索图像。

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

对此的任何示例或任何其他建议都会有所帮助。

【问题讨论】:

  • bytea 的 java 等效数据类型是 byte。这是正确的!
  • 您需要显示一些代码以获得帮助!
  • 我衷心推荐使用谷歌来寻找这种信息......
  • 完全按照您说的使用。我知道它完全有效。

标签: java image postgresql bytea


【解决方案1】:

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();

【讨论】:

【解决方案2】:

通过Java Database Connectivity API,这里是example 如何连接到 postgres 数据库。如有任何疑问.. 跟进!!

【讨论】:

    猜你喜欢
    • 2014-05-25
    • 2016-06-17
    • 1970-01-01
    • 1970-01-01
    • 2012-08-01
    相关资源
    最近更新 更多