1. 程式人生 > >java+pgsql實現儲存圖片到資料庫,以及讀取資料庫儲存的圖片

java+pgsql實現儲存圖片到資料庫,以及讀取資料庫儲存的圖片

複製程式碼
 1 /**
 2  * 
 3  */
 4 package com.hlcui.file;
 5 
 6 import java.io.FileInputStream;
 7 import java.io.InputStream;
 8 import java.sql.Connection;
 9 import java.sql.PreparedStatement;
10 import java.sql.ResultSet;
11 import java.sql.SQLException;
12 
13 /**
14  * @author Administrator 測試寫入資料庫以及從資料庫中讀取
15 */ 16 public class ImageDemo { 17 18 // 將圖片插入資料庫 19 public static void readImage2DB() { 20 String path = "D:/1.png"; 21 Connection conn = null; 22 PreparedStatement ps = null; 23 FileInputStream in = null; 24 try { 25 in = ImageUtil.readImage(path);
26 conn = DBUtil.getConn(); 27 String sql = "insert into photo (id,name,photo)values(?,?,?)"; 28 ps = conn.prepareStatement(sql); 29 ps.setInt(1, 1); 30 ps.setString(2, "Tom"); 31 ps.setBinaryStream(3, in, in.available()); 32 int
count = ps.executeUpdate(); 33 if (count > 0) { 34 System.out.println("插入成功!"); 35 } else { 36 System.out.println("插入失敗!"); 37 } 38 } catch (Exception e) { 39 e.printStackTrace(); 40 } finally { 41 DBUtil.closeConn(conn); 42 if (null != ps) { 43 try { 44 ps.close(); 45 } catch (SQLException e) { 46 e.printStackTrace(); 47 } 48 } 49 } 50 51 } 52 53 // 讀取資料庫中圖片 54 public static void readDB2Image() { 55 String targetPath = "D:/image/1.png"; 56 Connection conn = null; 57 PreparedStatement ps = null; 58 ResultSet rs = null; 59 try { 60 conn = DBUtil.getConn(); 61 String sql = "select * from photo where id =?"; 62 ps = conn.prepareStatement(sql); 63 ps.setInt(1, 1); 64 rs = ps.executeQuery(); 65 while (rs.next()) { 66 InputStream in = rs.getBinaryStream("photo"); 67 ImageUtil.readBin2Image(in, targetPath); 68 } 69 } catch (Exception e) { 70 e.printStackTrace(); 71 } finally { 72 DBUtil.closeConn(conn); 73 if (rs != null) { 74 try { 75 rs.close(); 76 } catch (SQLException e) { 77 e.printStackTrace(); 78 } 79 } 80 if (ps != null) { 81 try { 82 ps.close(); 83 } catch (SQLException e) { 84 e.printStackTrace(); 85 } 86 } 87 88 } 89 } 90 //測試 91 public static void main(String[] args) { 92 //readImage2DB(); 93 readDB2Image(); 94 } 95 }