jdbc读写二进制文件

来源:互联网 发布:淘宝网首页的分类 编辑:程序博客网 时间:2024/05/16 15:11

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;


public class BinTest {

 
 public static void main(String[] args) throwsIOException, SQLException
 {
  read();
 }
 private static void read() throws SQLException,IOException
 {
  Connection conn = null;
  PreparedStatement ps = null;
  ResultSet rs = null;
 
  try {
  conn =JdbcUtils.getConnection();
  
  String sql = "select con_binfrom blobtest";
  
  ps =conn.prepareStatement(sql);
  
  
  
  rs = ps.executeQuery();
  
  while (rs.next())
  {
   Blob b =rs.getBlob(1);
   
   InputStreamfi = rs.getBinaryStream(1);
   
   File file =new File("F:\\mysql官方ppt.pptx");
   FileOutputStreamfo = new FileOutputStream(file);
   BufferedOutputStreambo = new BufferedOutputStream(fo);
   byte[]buff  = new byte[1024];
   inti=0;
   while((i =fi.read(buff))>0)
   {
    bo.write(buff);
   }
   
   bo.close();
   fo.close();
   fi.close();
  }
  
  
  
  
 } finally
 {
  JdbcUtils.release(rs, ps,conn);
 }
 }
 
 private static void write() throws IOException,SQLException
 {
  Connection conn = null;
  PreparedStatement ps = null;
  ResultSet rs = null;
 
  try {
  conn =JdbcUtils.getConnection();
  
  String sql = "insert intoblobtest(con_bin) values (?)";
  
  ps =conn.prepareStatement(sql);
  
  File f = new File("E:\\MySQL—oracle学习中心.pptx");
  FileInputStream fi = newFileInputStream(f);
  BufferedInputStream bi = newBufferedInputStream(fi);
  
  ps.setBinaryStream(1,bi,f.length());
  
  int change_count =ps.executeUpdate();
  
  bi.close();
  fi.close();
  
  
  System.out.println(change_count);
  
 } finally
 {
  JdbcUtils.release(rs, ps,conn);
 }
 
 
 }
}

源文件:
jdbc读写二进制文件

写入数据库的效果;

jdbc读写二进制文件
从数据库读取的文件:

jdbc读写二进制文件

0 0
原创粉丝点击