jdbc读写二进制文件

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) throws IOException, 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_bin from blobtest";

 

 ps = conn.prepareStatement(sql);

 

 

 

 rs = ps.executeQuery();

 

 while (rs.next())

 {

  Blob b = rs.getBlob(1);

 

  InputStream fi = rs.getBinaryStream(1);

 

  File file = new File("F:\\mysql官方ppt.pptx");

  FileOutputStream fo = new FileOutputStream(file);

  BufferedOutputStream bo = new BufferedOutputStream(fo);

  byte[] buff  = new byte[1024];

  int i=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 into blobtest(con_bin) values (?)";

 

 ps = conn.prepareStatement(sql);

 

 File f = new File ("E:\\MySQL—oracle学习中心.pptx");

 FileInputStream fi = new FileInputStream(f);

 BufferedInputStream bi = new BufferedInputStream(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);

}

}

————————————————

版权声明:本文为CSDN博主「明明如月学长」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。

原文链接:https://blog.csdn.net/w605283073/article/details/46572491

上一篇:ArcGIS 读写lyr层文件


下一篇:PostgreSQL MySQL 数据类型映射