-JavaでBlobデータを扱う(Oracle)

package example;

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

public class TestBlob {

	static final String insertSQL = "INSERT INTO test_blob_data(id, data) VALUES(3, ?)";
	static final String selectSQL = "select id,data from test_blob_data where id = 3";
	static final String updateSQL = "UPDATE test_blob_data SET data = ? WHERE id = 3";

	static final String dbuser    = "user";
	static final String dbpass    = "pass";
	static final String constring = "jdbc:oracle:thin:@localhost:1521:orcl";

	// DBへ登録する画像ファイル
	static String insertFileName    = "c:/tmp/blob_insert.csv";

	// DBから読み込んだ画像データの出力先
	static String outputFileName    = "c:/tmp/blob_read.csv";
	
	public Connection db = null;

	/**
	 * メイン処理
	 */
	public static void main(String[] args) {

		try {
			// byte配列から登録(prepareCall)
			insertBlobFromBytes1(getByteArray(insertFileName));

			// byte配列から登録(ダイレクトサポート)
//			insertBlobFromBytes2(getByteArray(insertFileName));

			// 文字列から登録(ダイレクトサポート)
//			insertBlobFromString("あかさたな,はまやらわ,\r\nいきしちに,ふむうるう\r\n");

			// ファイルから登録(ダイレクトサポート)
//			insertBlobFromFile(insertFileName);

			// データ読み込み
			readBlob();

		} catch (Exception e){
			e.printStackTrace();
		}
	}

	/**
	 * BLOB読み込み
	 */
	public static void readBlob() throws Exception {

		Class.forName("oracle.jdbc.driver.OracleDriver");
		Connection con = DriverManager.getConnection(constring,dbuser,dbpass);
		PreparedStatement stmt = con.prepareStatement(selectSQL);

		boolean result = stmt.execute();
		ResultSet rs = stmt.getResultSet();
		while(rs.next()) {
			String id = rs.getString(1);
			Blob blob = rs.getBlob(2);
			InputStream in = blob.getBinaryStream();
			ByteArrayOutputStream baos = new ByteArrayOutputStream();

			int bytes;
			byte b[] = new byte[4096];
			while ((bytes = in.read(b)) != -1){
				baos.write(b, 0, bytes);
			}
			System.out.println(id + ":" + baos.toString());

			//
			byte[] b2 = blob.getBytes(1, (int)blob.length());
			String str = new String(b2);
			System.out.println(id + "(getBytes):" + str);
		}
		con.close();
	}

	/**
	 * BLOB登録
	 */
	public static void insertBlob(){
		
		File imgFile = null;
		
		//画像ファイルが有効であるかの判断
		try {
			imgFile = new File("/user/xxxx/test.txt");
			if (!imgFile.isFile()) {
				System.out.println("file not exists1!");
				return;
			}
		} catch (Exception e) {
			System.out.println("file not exists2!");
			return;
		}

		Connection con = null;
		PreparedStatement stmt1 = null;
		PreparedStatement stmt2 = null;

		try {

			Class.forName("oracle.jdbc.driver.OracleDriver");
			con = DriverManager.getConnection(constring,dbuser,dbpass);
			con.setAutoCommit(false);

			//画像フィールドの初期化
			stmt1 = con.prepareStatement("INSERT INTO test_blob_data(id, data) VALUES(2, EMPTY_BLOB())");
			int cnt = stmt1.executeUpdate();

			//画像フィールドのバインド
			stmt2 = con.prepareStatement("SELECT data FROM test_blob_data WHERE id = 2 FOR UPDATE");
			ResultSet rs = stmt2.executeQuery();
			rs.next();
			oracle.sql.BLOB blob = ((oracle.jdbc.driver.OracleResultSet)rs).getBLOB(1);

			//画像ファイルからのストリームの取得
			FileInputStream instream = new FileInputStream(imgFile);
			OutputStream outstream = blob.getBinaryOutputStream();

			//画像フィールドへの書き込み
			int chunk = blob.getChunkSize();
			byte[] buff = new byte[chunk];
			int le;
			while((le = instream.read(buff)) != -1) {
				outstream.write(buff,0,le);
			}
			
			instream.close();
			outstream.close();
			stmt2.close();
			stmt1.close();
			con.commit();
			con.close();
			con = null;

		} catch (SQLException e) {
			e.printStackTrace();
			return;
		} catch (Exception e) {
			e.printStackTrace();
			return;
		}
	}

	/**
	 * BLOB登録
	 * (prepareCallを利用してbyte配列から)
	 */
	public static void insertBlobFromBytes1(byte[] b) throws Exception {

		Connection con = null;
		Class.forName("oracle.jdbc.driver.OracleDriver");
		con = DriverManager.getConnection(constring,dbuser,dbpass);
		con.setAutoCommit(false);

		cstmt = con.prepareCall(
			"begin " +
			" update emp_lob set image = empty_blob() " +
			" where emp_no = ? " +
			" returning image into ?; " +
			"end;");
		cstmt.setInt(1, empno);
		cstmt.registerOutParameter(2, OracleTypes.BLOB);
		cstmt.executeQuery();
		BLOB blob = (BLOB)cstmt.getObject(2);
		blob.putBytes(1, data);
		con.commit();
		con.close();
	}

	/**
	 * BLOB登録
	 * (ダイレクトサポートを利用してファイルから)
	 */
	public static void insertBlobFromFile(String filePath) throws Exception {

		Connection con = null;
		Class.forName("oracle.jdbc.driver.OracleDriver");
		con = DriverManager.getConnection(constring,dbuser,dbpass);
		con.setAutoCommit(false);

		File file = new File(filePath);
		FileInputStream finstream = new FileInputStream(file);
		PreparedStatement stmt = con.prepareStatement(insertSQL);
		stmt.setBinaryStream(1, finstream, (int)file.length());
		int result = stmt.executeUpdate();

		stmt.close();
		con.commit();
		con.close();
	}

	/**
	 * BLOB登録
	 * (ダイレクトサポートを利用して文字列から)
	 */
	public static void insertBlobFromString(String str) throws Exception {

		Connection con = null;
		Class.forName("oracle.jdbc.driver.OracleDriver");
		con = DriverManager.getConnection(constring,dbuser,dbpass);
		con.setAutoCommit(false);
		
		ByteArrayInputStream bais = new ByteArrayInputStream(str.getBytes());
		PreparedStatement stmt = con.prepareStatement(insertSQL);
		stmt.setBinaryStream(1, bais, str.getBytes().length);
		int result = stmt.executeUpdate();

		stmt.close();
		con.commit();
		con.close();
	}

	/**
	 * BLOB登録
	 * (ダイレクトサポートを利用してbyte配列から)
	 */
	public static void insertBlobFromBytes2(byte[] b) throws Exception {

		Connection con = null;
		Class.forName("oracle.jdbc.driver.OracleDriver");
		con = DriverManager.getConnection(constring,dbuser,dbpass);
		con.setAutoCommit(false);

		ByteArrayInputStream bais = new ByteArrayInputStream(b);
		PreparedStatement stmt = con.prepareStatement(insertSQL);
		stmt.setBinaryStream(1, bais, b.length);
		int result = stmt.executeUpdate();

		stmt.close();
		con.commit();
		con.close();
	}

	/**
	 * ファイル内容をbyte配列で取得する
	 * @param filePath
	 * @return byte[]
	 * @throws Exception
	 */
	public static byte[] getByteArray(String filePath) throws Exception {
		
		StringBuffer sb = new StringBuffer();
		BufferedReader reader = new BufferedReader(new FileReader(filePath));
		String rec = null;
		while ((rec = reader.readLine()) != null) {
			sb.append(reader.readLine());
		}
		return sb.toString().getBytes();
	}

}

トップ   差分 バックアップ リロード   一覧 単語検索 最終更新   ヘルプ   最終更新のRSS
Last-modified: 2009-06-11 (木) 00:48:28 (5427d)