大二进制数据的存取
1 package cn.itcast.jdbc.lob; 2 3 import java.io.File; 4 import java.io.FileInputStream; 5 import java.io.FileOutputStream; 6 import java.io.FileReader; 7 import java.io.FileWriter; 8 import java.io.InputStream; 9 import java.io.OutputStream; 10 import java.io.Reader; 11 import java.io.Writer; 12 import java.sql.Connection; 13 import java.sql.PreparedStatement; 14 import java.sql.ResultSet; 15 16 import org.junit.Test; 17 18 import cn.itcast.util.JdbcUtil; 19 20 //大二进制数据的存取 21 /* 22 use day15; 23 create table t2( 24 id int primary key, 25 content longblob 26 ); 27 */ 28 public class BlobDemo { 29 @Test 30 public void testAdd(){ 31 Connection conn = null; 32 PreparedStatement stmt = null; 33 try{ 34 conn = JdbcUtil.getConnection(); 35 stmt = conn.prepareStatement("insert into t2 (id,content) values (?,?)"); 36 stmt.setInt(1, 1); 37 38 InputStream in = new FileInputStream("c:/1.jpg"); 39 stmt.setBinaryStream(2, in, in.available()); 40 41 int i = stmt.executeUpdate(); 42 if(i>0) 43 System.out.println("插入成功"); 44 45 }catch(Exception e){ 46 e.printStackTrace(); 47 }finally{ 48 JdbcUtil.release(null, stmt, conn); 49 } 50 } 51 @Test 52 public void testRead(){ 53 Connection conn = null; 54 PreparedStatement stmt = null; 55 ResultSet rs = null; 56 try{ 57 conn = JdbcUtil.getConnection(); 58 stmt = conn.prepareStatement("select * from t2 where id=?"); 59 stmt.setInt(1, 1); 60 //大数据要使用流的形式 61 //保存到E盘上 62 rs = stmt.executeQuery(); 63 if(rs.next()){ 64 InputStream in = rs.getBinaryStream("content"); 65 OutputStream out = new FileOutputStream("e:/1.jpg"); 66 byte b[] = new byte[1024]; 67 int len = -1; 68 while((len=in.read(b))!=-1){ 69 out.write(b, 0, len); 70 } 71 out.close(); 72 in.close(); 73 } 74 75 }catch(Exception e){ 76 e.printStackTrace(); 77 }finally{ 78 JdbcUtil.release(null, stmt, conn); 79 } 80 } 81 }