2012-07-02 87 views
3

我想知道如何在我的postgresql表中的某個字段上插入圖像。這個問題我找不到合適的教程。該字段的數據表是oid。有沒有人試過這個?謝謝!如何在postgresql中插入圖片?

+3

在檢查方法之前,請考慮爲什麼要在數據庫中存儲圖像。將圖像存儲在數據庫中並不是一個好主意http://stackoverflow.com/questions/3748/storing-images-in-db-yea-or-nay – 18bytes

+0

@devsundar:這樣做是有正當理由的。有時它實際上更快。 –

+0

@a_horse_with_no_name不從文件系統訪問映像比從數據庫訪問映像快嗎?如果你能提到一個關鍵的原因,這對每個人都有用。 – 18bytes

回答

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,然後您需要將其存儲在另一個表中以跟蹤它們。