3

我想知道如何在我的 postgresql 表中的一个字段上插入图像。我找不到合适的教程来解决这个问题。该字段的数据类型是oid. 有没有人试过这个?谢谢!

4

3 回答 3

3
// All LargeObject API calls must be within a transaction
conn.setAutoCommit(false);

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

//create a new large object
int oid = lobj.create(LargeObjectManager.READ | LargeObjectManager.WRITE);

//open the large object for write
LargeObject obj = lobj.open(oid, LargeObjectManager.WRITE);

// Now open the file
File file = new File("myimage.gif");
FileInputStream fis = new FileInputStream(file);

// copy the data from the file to the large object
byte buf[] = new byte[2048];
int s, tl = 0;
while ((s = fis.read(buf, 0, 2048)) > 0)
{
        obj.write(buf, 0, s);
        tl += s;
}

// Close the large object
obj.close();

//Now insert the row into imagesLO
PreparedStatement ps = conn.prepareStatement("INSERT INTO imagesLO VALUES (?, ?)");
ps.setString(1, file.getName());
ps.setInt(2, oid);
ps.executeUpdate();
ps.close();
fis.close();

从这里找到示例代码。真的很不错的一堆sql操作。

于 2012-07-02T06:50:36.977 回答
2

引用本网站

PostgreSQL 数据库有一种特殊的数据类型来存储二进制数据,称为 bytea。这是一种非标准数据类型。数据库中的标准数据类型是 BLOB。

你需要编写一个客户端来读取图像文件,例如

File img = new File("woman.jpg");
fin = new FileInputStream(img);

con = DriverManager.getConnection(url, user, password);

pst = con.prepareStatement("INSERT INTO images(data) VALUES(?)");
pst.setBinaryStream(1, fin, (int) img.length());
pst.executeUpdate();
于 2012-07-02T06:53:22.767 回答
1

您可以使用bytea类型或大型对象工具。但是请注意,根据您的用例,将图像放入数据库可能不是一个好主意,因为它可能会给数据库服务器带来额外的负载。

重读您的问题,我注意到您提到您有一个 oid 类型的字段。如果这是您正在修改的应用程序,它向我表明它正在使用大型对象。这些对象得到一个 oid,然后您需要将其存储在另一个表中以跟踪它们。

于 2012-07-02T06:57:31.633 回答