我想知道如何在我的postgresql表中的某個字段上插入圖像。這個問題我找不到合適的教程。該字段的數據表是oid
。有沒有人試過這個?謝謝!如何在postgresql中插入圖片?
3
A
回答
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操作。
+2
請不要鏈接到完全過時的版本(7.3)。改爲使用當前的JDBC手冊:http://jdbc.postgresql.org/documentation/91/binary-data.html –
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();
1
您可以使用bytea類型或large objects設施。但請注意,根據您的使用情況,將圖像放入數據庫可能不是一個好主意,因爲可能會將其添加到數據庫服務器上。
重新讀你的問題我發現你提到你有一個oid類型的字段。如果這是一個正在修改的應用程序,則向我建議它正在使用大型對象。這些對象獲得一個oid,然後您需要將其存儲在另一個表中以跟蹤它們。
相關問題
- 1. 如何添加圖片框並在圖片中插入文字?
- 2. 在android中插入圖片
- 3. 如何在postgreSQL pgAdmin中插入一行?
- 4. 如何插入PNG圖片中的iPhone
- 5. 插入圖片
- 6. 如何將圖片或圖片插入到oracle數據庫中?
- 7. Office插件開發:在Word 2016中插入圖片/圖片
- 8. 在圖片框中插入圖標
- 9. 在表格視圖中插入圖片?
- 10. 在PostgreSQL中插入緩慢
- 11. 用nodejs在PostgreSql中插入
- 12. 如何使用循環插入PostgreSQL中
- 13. 插入圖片在powerpoint
- 14. 如何正確插入背景圖片
- 15. 如何將圖片插入使用WPF
- 16. 如何插入圖片到EDITTEXT
- 17. 如何在html中的另一張圖片上插入一張圖片?
- 18. 如何在圖片框中直接插入圖片到sql數據庫vb dotnet
- 19. 在html菜單中插入圖片
- 20. 在流星中插入圖片
- 21. 在描述中插入圖片庫
- 22. 在MigraDoc表中插入「http」圖片
- 23. 插入圖片在Microsoft Office Word中.docx
- 24. 如何讓excel在Applescript中插入新圖片?
- 25. 如何在html動作鏈接中插入圖片? asp.net mvc
- 26. 如何在php郵件中插入圖片?
- 27. 如何在呼叫意圖中插入照片?
- 28. 如何在wpf路徑中插入圖片?
- 29. 如何在HAML中直接從URL插入圖片?
- 30. 如何在郵件正文中插入圖片
在檢查方法之前,請考慮爲什麼要在數據庫中存儲圖像。將圖像存儲在數據庫中並不是一個好主意http://stackoverflow.com/questions/3748/storing-images-in-db-yea-or-nay – 18bytes
@devsundar:這樣做是有正當理由的。有時它實際上更快。 –
@a_horse_with_no_name不從文件系統訪問映像比從數據庫訪問映像快嗎?如果你能提到一個關鍵的原因,這對每個人都有用。 – 18bytes