日期:2014-05-16 浏览次数:20424 次
//写入图片到数据库 static void insert() throws Exception { String sql ="insert into pics (pic) values (?)"; Connection conn=JdbcUtilSingle.getConnection(); PreparedStatement pst=conn.prepareStatement(sql); File file = new File("p_large_CuRa_47110000afc8121a.jpg"); InputStream inputstream = new BufferedInputStream(new FileInputStream(file)); pst.setBinaryStream(1, inputstream, (int)file.length());//说明:这里一定要转化为int,否则会报错,length()返回值为long类型的 //setBinaryStream(1, inputstream,(long)file.length()); int i = pst.executeUpdate(); System.out.println(i); JdbcUtilSingle.free(null, pst, conn); } //读出图片信息 static void write() throws Exception { String sql="select * from pics "; Connection conn=JdbcUtilSingle.getConnection(); PreparedStatement pst=conn.prepareStatement(sql); ResultSet rs=pst.executeQuery(); File file = new File("mypic.jpg"); while(rs.next()) { //Blob blob = rs.getBlob(1); //InputStream in = blob.getBinaryStream(); //上面兩行的作用和下面這行相同 InputStream in = rs.getBinaryStream(1); OutputStream out = new BufferedOutputStream(new FileOutputStream(file)); byte buff[]= new byte[1024]; //寫入文件 for(int i=0;(i=in.read(buff))>0;) { out.write(buff, 0, i); } } JdbcUtilSingle.free(rs, pst, conn);?