标签:
数据库准备:
create table blob_test ( id integer not null auto_increment, big_bit blob not null, primary key(id) );
在工程目录下新建一个images文件夹,存入一张zhukov.jpg图片
向数据库插入二进制数据:
1 public static void create() throws SQLException, IOException { 2 Connection conn = null; 3 PreparedStatement ps = null; 4 ResultSet rs = null; 5 try { 6 conn = JdbcUtils.getConnection(); 7 8 String sql = "insert into blob_test(big_bit) values(?)"; 9 ps = conn.prepareStatement(sql); 10 File file = new File("src/images/zhukov.jpg"); 11 InputStream in = new BufferedInputStream(new FileInputStream(file)); 12 ps.setBinaryStream(1, in, (int)file.length()); 13 int i = ps.executeUpdate(); 14 in.close(); 15 System.out.println("i~~~~~" + i); 16 } finally { 17 JdbcUtils.close(rs, ps, conn); 18 } 19 20 }
public static void read() throws IOException, SQLException { Connection conn = null; Statement stmt = null; ResultSet rs = null; try { conn = JdbcUtils.getConnection(); stmt = conn.createStatement(); String sql = "select big_bit from blob_test"; rs = stmt.executeQuery(sql); while(rs.next()) { InputStream in = rs.getBinaryStream(1); File file = new File("src/images/zhukov_bak.png"); OutputStream out = new BufferedOutputStream(new FileOutputStream(file)); byte[] buffer = new byte[1024]; for (int i = 0; (i=in.read(buffer))>0; ) { out.write(buffer, 0, i); } out.close(); in.close(); } } finally { JdbcUtils.close(rs, stmt, conn); } }
刷新工程,将在images目录下增加了zhukov_bak.png
标签:
原文地址:http://www.cnblogs.com/xiaoxiaoyihan/p/4351344.html