首页 > 代码库 > 用jdbc访问二进制类型的数据
用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 }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。