java保存大对象到数据库

/*
    把图片存入类型为BLOB大数据类型的表中!
*/

package com.test;

import java.sql.*;
import oracle.sql.*;
import java.io.*;

public class H4
{
	public static void main(String[] args) throws Exception
	{
		Class.forName("oracle.jdbc.driver.OracleDriver");
		Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@192.168.6.6:1521:orcl","scott","tiger");
		PreparedStatement ps = conn.prepareStatement("insert into y02 (id,name,photo) values (1,'1.jpg',empty_lob())");
		ps.executeUpdate();
		String sql = "select photo from y02 where id = 1 for update";
		ps = conn.prepareStatement(sql);
		ResultSet rs = ps.executeQuery();
		rs.next();
		BLOB b1 = (BLOB)rs.getBlob("photo");
		InputStream is = new FileInputStream("1.jpg");
		System.out.println(is.available());
		OutputStream os = b1.getBinaryOutputStream();
		byte[] b2 = new byte[1024*100];
		int len = -1;
		while ((len = is.read(b2)) != -1)
		{
			
			os.write(b2,0,len);
			os.flush();
		}
		
		ps = conn.prepareStatement("update y02 set photo = ?");
		ps.setBlob(1,b1);
		ps.executeUpdate();
		System.out.println(is.available());
		conn.close();
	}
};

 

/*
    把读取存入类型为BLOB大数据类型的表中!
*/

package com.test;

import java.sql.*;
import oracle.sql.*;
import java.io.*;

public class H5
{
	public static void main(String[] args) throws Exception
	{
		Class.forName("oracle.jdbc.driver.OracleDriver");
		Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@192.168.6.6:1521:orcl","scott","tiger");
		
		String sql = "select photo from y02 where id = 1";
		PreparedStatement ps = conn.prepareStatement(sql);
		ResultSet rs = ps.executeQuery();
		rs.next();
		BLOB b1 = (BLOB)rs.getBlob("photo");
		
		
		InputStream is = b1.getBinaryStream();
		
		FileOutputStream fos = new FileOutputStream("20.jpg");
		byte[] b2 = new byte[1024*100];
		int len = -1;
		while ((len = is.read(b2)) != -1)
		{
			fos.write(b2,0,len);
		}
		
		
		conn.close();
	}
};

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值