如何在postgresql中插入图像?

时间:2012-07-02 06:40:44

标签: sql postgresql

我想知道如何在postgresql表中的一个字段上插入图像。这件事我找不到合适的教程。该字段的dataype为oid。有没人试过这个?谢谢!

3 个答案:

答案 0 :(得分: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();

找到here的示例代码。非常好的一堆sql操作。

答案 1 :(得分:2)

引用this site

  

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

答案 2 :(得分:1)

您可以使用bytea类型或large objects工具。但请注意,根据您的使用情况,将图像放入数据库可能不是一个好主意,因为它可能会在数据库服务器上产生额外负载。

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