การอ่านและแสดงรูปภาพใน PostGreSQL
posted on 14 Oct 2004 17:58 by somkiatDocument Storing Binary in PostGreSQL http://www.postgresql.org/docs/7.4/static/jdbc-binary-data.html JDBC Driver for PostGreSQL http://jdbc.postgresql.org/download.html Document of JDBC http://jdbc.postgresql.org/documentation/pgjdbc.html
Requirementต้องการบันทึกแสดงแสดงข้อมูลชนิด Binary ที่เก็บในฐานข้อมูล PostGreSQL
Solution1. สร้าง Database ที่สนับสนุน Unicode Character Encoding 2. สร้าง table สำหรับเก็บข้อมูลชนิด binary ดังนี้
CREATE TABLE test(
name text, //ชื่อ file
pic oid //เก็บข้อมูล binary)
3. สร้าง code สำหรับการบันทึกข้อมูล binary ลงฐานข้อมูล ดังนี้
private void SavePicture() {
Connection conn = null;
try {
conn = getConnection();
conn.setAutoCommit(false);
//Create Large object manager
LargeObjectManager manager = ( ( PGConnection ) conn ).getLargeObjectAPI();
int oid = manager.create(LargeObjectManager.READ | LargeObjectManager.WRITE);
LargeObject obj = manager.open(oid, LargeObjectManager.WRITE);
//Read picture from file
File file = new File("P1020156.JPG");
FileInputStream in = new FileInputStream(file);
//Copy the data from the file to the large object
byte buf[] = new byte[2048];
int s, tl = 0;
while ((s = in.read(buf, 0, 2048)) > 0) {
obj.write(buf, 0, s);
tl += s;
}
obj.close();
PreparedStatement prepStmt = conn.prepareStatement("Insert into test values(?,?)");
prepStmt.setString(1, file.getName());
prepStmt.setInt(2, oid);
prepStmt.executeUpdate();
prepStmt.close();
in.close();
conn.commit();
conn.setAutoCommit(true);
conn.close();
} catch( Exception e ) {
e.printStackTrace();
}
}
4. สร้าง code สำหรับการดึงหรืออ่านข้อมูล binary จากฐานข้อมูล ดังนี้
public byte[] getData(){
Connection conn = null;
Vector keep = new Vector();
byte buf[] = null;
try {
conn = getConnection();
conn.setAutoCommit(false);
LargeObjectManager manager = ( ( PGConnection ) conn ).getLargeObjectAPI();
PreparedStatement prepStmt = conn.prepareStatement("select pic from test");
ResultSet result = prepStmt.executeQuery();
if(result.next()) {
int oid = result.getInt(1);
System.out.println(oid);
LargeObject obj = manager.open(oid, LargeObjectManager.READ);
//Read the data
buf = new byte[obj.size()];
obj.read(buf, 0, obj.size());
obj.close();
}
result.close();
result = null;
prepStmt.close();
prepStmt = null
; } catch(Exception e) {
System.out.println("Error in getData() method > " + e.getMessage());
e.printStackTrace();
} finally {
try {
if(conn != null) {
conn.close();
conn = null;
}
} catch(SQLException sqle) {
System.out.println("Error in getData() method > " + sqle.getMessage());
sqle.printStackTrace();
}
}
return buf;
}
//SErvlet Code
//Set contenttype of response
response.setContentType("image/jpeg");
OutputStream out = response.getOutputStream();
out.write(getData());
out.flush();
out.close();

#1 By เด็กมออุบล (61.90.244.140) on 2005-08-29 09:40