1. 程式人生 > >blob與string型別的相互轉換

blob與string型別的相互轉換

<pre name="code" class="java">
</pre><pre name="code" class="java">package com.coci.test2;

import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;

import oracle.sql.BLOB;

/**
 * 
 * @author Coci
 *
 */
public class TestBlob {

	public static void main(String[] args) {

		// blob記憶體放的是位元組陣列
		// String 的getBytes方法獲得該字串的位元組陣列(注意編碼),然後存入blob即可
		String blobStr = "blob";
		byte[] bytes = null;
		try {
			bytes = blobStr.getBytes("utf-8");
			System.out.println("===" + bytes);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		instertData(bytes);

		// 從資料庫中讀取Blob型別資料後,要轉換成String型別,即轉換成InputStream,再從InputStream轉成byte[],再到String即可。
		// blob轉換成String
//		String result = "";
//		try {
//			ByteArrayInputStream msgContent = (ByteArrayInputStream) blob
//					.getBinaryStream();
//			byte[] byte_data = new byte[msgContent.available()];
//			msgContent.read(byte_data, 0, byte_data.length);
//			result = new String(byte_data);
//		} catch (SQLException e) {
//			e.printStackTrace();
//		}
	}

	@SuppressWarnings("deprecation")
	public static void instertData(byte[] value) {
		// TODO Auto-generated method stub
		try {
			Class.forName("oracle.jdbc.driver.OracleDriver");
			String url = "jdbc:oracle:thin:@10.211.19.71:1521:orcl";
			String username = "yst";
			String password = "yst";
			Connection con = DriverManager.getConnection(url, username,
					password);
			con.setAutoCommit(false);
			String sql1 = "insert into testcoci(id,name) values('88',empty_blob())";

			Statement statement = con.createStatement();
			boolean b2 = statement.execute(sql1);
			System.out.println("第一次===" + b2);

			String sql2 = "select name from testcoci where id=88 for update";
			PreparedStatement stmt = con.prepareStatement(sql2);
			ResultSet rs = stmt.executeQuery();
			OutputStream outStream = null;
			if (rs.next()) {

				System.out.println("進來了");
				BLOB blob = (BLOB) rs.getBlob(1);
				System.out.println("資料庫  blob =" + blob + "=");
				outStream = blob.getBinaryOutputStream();
				outStream.write(value, 0, value.length);
			}
			outStream.flush();
			outStream.close();
			con.commit();
			con.close();

		} catch (Exception e) {
			System.out.println(e.getCause());
		}
	}
}