2018.7.30 Oracle的Blog数据库类型读取和存

package com.lanqiao.shopping.test;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
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 com.lanqiao.shopping.utils.DBHelper;

public class Test {
	static PreparedStatement pstmt = null;
	static ResultSet rs = null;
	/*
	 * 创建图片的表myPicture
	 * 	   create  table myPicture(id number(4) primary key,img blob);
	 */
	
	//将图片写进数据库
	public static void writeImgToBolb(){
		Connection conn = DBHelper.getConn();
		String sql = "insert into myPicture(id,img) values(?,?)";
		
		try {
			pstmt = conn.prepareStatement(sql);
			pstmt.setInt(1,3);//id
			
			//将图片转为输入流
			File file = new File("D:\Eclipse\ImagesSave\one.jpg");
			InputStream in = new FileInputStream(file);
			
			/*
			String a = "sss";
			System.out.println(a.length());//字符串是length方法
			int[] i = new int[5];//数组是length属性
			System.out.println(i.length);*/
			
			
			//将输入流写入到myPicture表
			pstmt.setBinaryStream(2, in,(int)file.length());
			
			int result = pstmt.executeUpdate();
			System.out.println("111");
			if(result>0){
				System.out.println("图片写入成功");
			}else{
				System.out.println("图片写入失败");
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			DBHelper.closeConn(null, pstmt, conn);
		}
		
	}
	
	//从数据库读取图片
	public static void readImgToBlob(){
		Connection conn = DBHelper.getConn();
		String sql = "select * from myPicture where id=?";
		try {
			pstmt = conn.prepareStatement(sql);
			pstmt.setInt(1, 1);//id =1
			rs = pstmt.executeQuery();
			if(rs.next()){
				//将图片从数据库中读取出来,类型为InputStream
				InputStream imgIn = rs.getBinaryStream("img");
				
				//通过IO流,将图片写到项目中(硬盘)
				InputStream in = new BufferedInputStream(imgIn);
				
				//将图片的输出路径设置为src(相对路径),图片名为myPic.png
				OutputStream imgOut = new FileOutputStream("D:\Eclipse\ImagesSave\myPic.jpg");
				OutputStream out = new BufferedOutputStream(imgOut);
				
				int len = -1;
				while((len=in.read())!=-1){
					out.write(len);
				}
				
				imgOut.close();
				out.close();
				imgIn.close();
				in.close();
				System.out.println("照片读取成功");
				
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			DBHelper.closeConn(rs, pstmt, conn);
		}
		
	}
	
	public static void main(String[] args) {
		//writeImgToBolb();
		readImgToBlob();
	}
}

原文地址:https://www.cnblogs.com/qichunlin/p/9350394.html