首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在postgresql中插入图像?

如何在postgresql中插入图像?
EN

Stack Overflow用户
提问于 2012-07-02 14:40:44
回答 3查看 10.7K关注 0票数 3

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

EN

回答 3

Stack Overflow用户

发布于 2012-07-02 14:50:37

代码语言:javascript
运行
复制
// 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操作。

票数 3
EN

Stack Overflow用户

发布于 2012-07-02 14:53:23

引用this site的话:

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

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

代码语言:javascript
运行
复制
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
EN

Stack Overflow用户

发布于 2012-07-02 14:57:32

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

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11288827

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档