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());
		}
	}
}



                
  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值