码迷,mamicode.com
首页 > 数据库 > 详细

java读取oracle数据库中blob字段

时间:2015-01-29 22:36:18      阅读:301      评论:0      收藏:0      [点我收藏+]

标签:java   oracle   blob   

测试表

create table TEST_IMG
(
  ID    INTEGER not null,
  NAME  VARCHAR2(32),
  IMAGE BLOB
);

说明:

1、使用JDBC演示

2、IMAGE字段存储一个图片


程序代码如下:

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class Test {

	public static final String DRIVER = "oracle.jdbc.driver.OracleDriver";
	public static final String URL = "jdbc:oracle:thin:@127.0.0.1:1521:orcl";
	public static final String USERNAME = "test";
	public static final String PASSWORD = "test";

	static {
		try {
			Class.forName(DRIVER);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		if (download()) {
			System.out.println("图片下载成功");
		} else {
			System.out.println("图片下载失败");
		}
	}

	public static boolean download() {
		Connection conn = getConnection();
		Statement sta = null;
		ResultSet rs = null;
		try {
			sta = conn.createStatement();
			// image字段为BLOG字段
			String sql = "Select name, image from test_img where id=‘1‘";
			rs = sta.executeQuery(sql);
			while (rs.next()) {
				// 输出文件名
				String name = rs.getString("name");
				oracle.sql.BLOB blob = (oracle.sql.BLOB) rs.getBlob("image");
				String filepath = "D:/" + name + ".jpg";
				System.out.println("输出文件路径为:" + filepath);

				InputStream input = blob.getBinaryStream();
				FileOutputStream out = new FileOutputStream(filepath);
				int len = (int) blob.length();
				byte buffer[] = new byte[len];
				while ((len = input.read(buffer)) != -1) {
					out.write(buffer, 0, len);
				}
				out.close();
				input.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
			return false;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return false;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		} finally {
			try {
				rs.close();
				sta.close();
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
				return false;
			}
		}
		return true;
	}

	/**
	 * 获得Connection
	 */
	public static Connection getConnection() {
		Connection conn = null;
		try {
			conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return conn;
	}

}

存入图片Blob参见:Oracle JDBC存入图片Blob

作者:itmyhome


java读取oracle数据库中blob字段

标签:java   oracle   blob   

原文地址:http://blog.csdn.net/itmyhome1990/article/details/43227305

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!