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