用jdbc访问二进制类型的数据

 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 }
BlobTest

 

用jdbc访问二进制类型的数据,古老的榕树,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。