1 package it.cast.jdbc; 2 3 import java.io.BufferedInputStream; 4 import java.io.BufferedOutputStream; 5 import java.io.File; 6 import java.io.FileInputStream; 7 import java.io.FileOutputStream; 8 import java.io.InputStream; 9 import java.io.OutputStream; 10 import java.sql.Connection; 11 import java.sql.PreparedStatement; 12 import java.sql.ResultSet; 13 import java.sql.Statement; 14 15 public class BlobTest { 16 17 public static void main(String[] args) { 18 read(); 19 } 20 21 static void create() { 22 Connection conn = null; 23 PreparedStatement ps = null; 24 ResultSet rs = null; 25 26 try { 27 // 建立连接 28 conn = jdbcUtils.getConnection(); 29 30 // 创建语句 31 String sql = "insert into blob_test(big_bit) values(?)"; 32 ps = conn.prepareStatement(sql); 33 File file = new File("ww.gif"); 34 InputStream in = new BufferedInputStream(new FileInputStream(file)); 35 36 ps.setBinaryStream(1, in, (int) file.length()); 37 38 // 执行语句 39 int i = ps.executeUpdate(); 40 41 System.out.println(i); 42 43 in.close(); 44 } catch (Exception e) { 45 System.out.println("error"); 46 } finally { 47 jdbcUtils.free(rs, ps, conn); 48 } 49 50 } 51 52 static void read() { 53 Connection conn = null; 54 Statement st = null; 55 ResultSet rs = null; 56 57 try { 58 // 建立连接 59 conn = jdbcUtils.getConnection(); 60 61 // 创建语句 62 st = conn.createStatement(); 63 64 String sql = "select big_bit from blob_test"; 65 66 // 执行语句 67 rs = st.executeQuery(sql); 68 69 while (rs.next()) { 70 InputStream in = rs.getBinaryStream(1); 71 72 File file = new File("ww_bak.gif"); 73 74 OutputStream out = new BufferedOutputStream( 75 new FileOutputStream(file)); 76 byte[] buff = new byte[1024]; 77 78 for (int i = 0; (i = in.read()) > 0;) { 79 out.write(buff, 0, 1); 80 } 81 in.close(); 82 out.close(); 83 } 84 85 } catch (Exception e) { 86 System.out.println("error"); 87 } finally { 88 jdbcUtils.free(rs, st, conn); 89 } 90 91 } 92 93 }