JDBC 处理 Blob数据

MySQL BLOB 是一个二进制大型对象,是一个可以存储大量数据的容器,它能容纳不同大小的数据。

MySQL 的四种BLOB类型

TinyBLOB:最大255
BLOB:最大 65K
MediumBLOB:最大 16M
LongBLOB:最大 4G

/**
  * 查询数据表中的 Blob 类型的字段
  */
public void testQuery(){
	  Connection connection = null;
	  PreparedStatement preparedStatement = null;
	  ResultSet rs = null;
	  InputStream is = null;
	  FileOutputStream fos = null;
	  try {
		   //获取数据库连接
		   connection = JDBCTools.getConnection();
		  //准备SQL语句
		   String sql = "select name,address,picture from customers where id = ?";
		   preparedStatement = connection.prepareStatement(sql);
		   //填充占位符
		   preparedStatement.setInt(1, 44);
		   //查询操作
		   rs = preparedStatement.executeQuery();
		   if(rs.next()){
			    //获取结果集并封装对象
			    String name = rs.getString(1);
			    String address = rs.getString(2);
			    Customer customer = new Customer(name, address);
			    System.out.println(customer);
			    //使用 getBlob() 方法读取到 Blob 对象
			    Blob picture = rs.getBlob(3);
			    //调用 Blob 的 getBinaryStream() 方法得到输入流
			    is = picture.getBinaryStream();
			    //将得到的图片通过字节流下载到本地
			    fos = new FileOutputStream("123.jpg");
			    byte[] buffer = new byte[1024];
			    int len;
			    while((len = is.read(buffer)) != -1){
			     	fos.write(buffer,0,len);
			    }
		   }
	   } catch (Exception e) {
	   	e.printStackTrace();
	  } finally{
	   	JDBCTools.release(rs, preparedStatement, connection);
	  }
 }	
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值