12_传智播客JDBC_用jdbc访问二进制类型的数据

package five.base;

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

import five.utils.Utils;

//jdbc访问其他各种数据类型.参看数据库文档 例如23.3. MySQL Connector/J
// 图片 压缩包
public class ClobTest {

 /**
  * @param args
  * @throws Exception
  */
 public static void main(String[] args) throws Exception {

  // create(3, "F:/下载/picture/X.bmp");
  read(3);

 }

 public static void create(int id, String fileName) throws IOException {

  Connection connection = null;

  PreparedStatement ps = null;

  ResultSet rs = null;
  try {
   connection = Utils.getConnection();
   String sql = "insert into picture (id, picture) values (?,?)";
   ps = connection.prepareStatement(sql);

   File file = new File(fileName);
   // 字节流
   InputStream in = new BufferedInputStream(new FileInputStream(file));

   ps.setInt(1, id);
   // 前提 Ascii
   // parameterIndex - the first parameter is 1, the second is 2, ...
   // x - the Java input stream that contains the ASCII parameter value
   // length - the number of bytes in the stream
   // ps.setAsciiStream(2, x, length);

   // 字节流
   ps.setBinaryStream(2, in, (int) file.length());
   int i = ps.executeUpdate();
   in.close();
  } catch (SQLException e) {
   e.printStackTrace();
  } finally {
   Utils.free(connection, ps, rs);
  }
 }

 static void read(int id) throws Exception {

  // 避免依赖 应该使用接口(java.sql)的提供的类型
  Connection connection = null;
  PreparedStatement ps = null;
  ResultSet rs = null;

  try {
   // 2 创建连接
   connection = Utils.getConnection();
   // 3 创建语句
   String sql = "select picture  from picture ";
   ps = connection.prepareStatement(sql);

   // 4 执行语句
   rs = ps.executeQuery();
   // 5 处理结果
   while (rs.next()) {
    // Blob blob = rs.getBlob(1);
    // InputStream blobIn = blob.getBinaryStream();
    // 等价于上面的语句
    InputStream in = rs.getBinaryStream(1);
    
    // rs.getCharacterStream(2);
    File file = new File("D:/cgz/dayByDayJdbc/picture.bmp");
    // 装饰模式
    // Writer writer = new BufferedWriter(new FileWriter(file));
    OutputStream out = new BufferedOutputStream(
      new FileOutputStream(file));

    // 字符流 new char[1024]
    // 字节流 new byte[1024];
    byte[] buff = new byte[1024];
    for (int i = 0; (i = in.read(buff)) > 0;) {
     out.write(buff, 0, i);
    }
    out.close();
    in.close();
   }

  } finally {
   Utils.free(connection, ps, rs);
  }
 }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值