Oracle Clob类型和Blob类型之间的转换

目录

一、背景

二、Clob 和 Blob 的区别

三、使用JDK的Base64编码

四、使用Oracle自带的Base64编码

 


一、背景

最近在迁移数据时,遇到了将Clob类型转换成Blob的问题,历史数据中文件内容是使用Clob类型存储,而新表使用的Blob类型,这样就导致在迁移文件时需要将类型转换。

二、Clob 和 Blob 的区别

BLOB和CLOB都是大字段类型,BLOB是按二进制来存储的,而CLOB是可以直接存储文字的。两者可以相互替换。我们一般,将通常像图片、文件、音乐等信息就用BLOB字段来存储,将文章或者是较长的文字,就用CLOB存储。这样对方便以后的查询更新存储等操作。

三、使用JDK的Base64编码

在JDK1.8之前,base64编码解码是使用sun.misc.BASE64Decoder和sun.misc.BASE64Encoder,而在JDK1.8以及以后,则java.util.Base64.Decoder和java.util.Base64.Encoder替换了原来的。代码实现如下:

package com.lzw.demo;

import java.util.Base64;

public class ClobToBlob {

	public static void main(String[] args) {
		
		AttachmentBlob attachmentBlob = new AttachmentBlob();
		AttachmentClob attachmentClob = new AttachmentClob();
		//Clob 转 Blob
		byte[] decode = Base64.getMimeDecoder().decode(attachmentClob.getContent());
		attachmentBlob.setData(decode);
		attachmentBlob.setId(attachmentClob.getId());
		//Blob 转 Clob
		String content = Base64.getMimeEncoder().encodeToString(attachmentBlob.getData());
		attachmentClob.setContent(content);
	}
}

class AttachmentClob{
	private String id;
	private String content;
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getContent() {
		return content;
	}
	public void setContent(String content) {
		this.content = content;
	}
	
}

class AttachmentBlob{
	private String id;
	private byte[] data;
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public byte[] getData() {
		return data;
	}
	public void setData(byte[] data) {
		this.data = data;
	}
}

四、使用Oracle自带的Base64编码

 1、base64 的加密函数

select utl_raw.cast_to_varchar2(utl_encode.base64_encode(utl_raw.cast_to_raw('abcdef'))) from dual;

/2、 base64 的解密函数

select utl_raw.cast_to_varchar2(utl_encode.base64_decode(utl_raw.cast_to_raw('YWJjZGVm'))) from dual;

 

猜你喜欢

转载自blog.csdn.net/weixin_42228950/article/details/103741964
今日推荐