我有一个带CLOB列的大表。文本数据现在存储在其中。但我想写二进制字符串。在那种情况下我会遇到某种麻烦吗?
编辑:
迁移到BLOB是不合适的 - 表格非常大。
答案 0 :(得分:3)
一般来说,你不能这样做。特别是如果您的数据库使用UTF-8(现在是默认值),您有许多与有效字符不匹配的位值,并且在插入和选择时它们将替换为占位符(通常为¿
)。
您可以做的是将二进制数据编码为Base64字符串。这是在仅支持文本(例如XML文件或SMTP邮件)的接口上传输二进制数据的一种非常常见的方法
使用此功能将二进制数据编码为文本:
FUNCTION EncodeBASE64(InBlob IN BLOB) RETURN CLOB IS
BlobLen INTEGER := DBMS_LOB.GETLENGTH(InBlob);
read_offset INTEGER := 1;
warning INTEGER;
amount INTEGER := 1440; -- must be a whole multiple of 3
-- size of a whole multiple of 48 is beneficial to get NEW_LINE after each 64 characters
buffer RAW(1440);
res CLOB := EMPTY_CLOB();
BEGIN
IF InBlob IS NULL OR NVL(BlobLen, 0) = 0 THEN
RETURN NULL;
ELSIF BlobLen <= 24000 THEN
RETURN UTL_RAW.CAST_TO_VARCHAR2(UTL_ENCODE.BASE64_ENCODE(InBlob));
ELSE
-- UTL_ENCODE.BASE64_ENCODE is limited to 32k, process in chunks if bigger
LOOP
EXIT WHEN read_offset >= BlobLen;
DBMS_LOB.READ(InBlob, amount, read_offset, buffer);
res := res || UTL_RAW.CAST_TO_VARCHAR2(UTL_ENCODE.BASE64_ENCODE(buffer));
read_offset := read_offset + amount;
END LOOP;
END IF;
RETURN res;
END EncodeBASE64;
这个函数转换回BLOB
FUNCTION DecodeBASE64(InBase64Char IN CLOB) RETURN BLOB IS
res BLOB;
clob_trim CLOB;
dest_offset INTEGER := 1;
src_offset INTEGER := 1;
read_offset INTEGER := 1;
ClobLen INTEGER := DBMS_LOB.GETLENGTH(InBase64Char);
amount INTEGER := 1440; -- must be a whole multiple of 4
buffer RAW(1440);
stringBuffer VARCHAR2(1440);
-- BASE64 characters are always simple ASCII. Thus you get never any Mulit-Byte character and having the same size as 'amount' is sufficient
BEGIN
IF InBase64Char IS NULL OR NVL(ClobLen, 0) = 0 THEN
RETURN NULL;
ELSIF ClobLen <= 32000 THEN
RETURN TO_BLOB(UTL_ENCODE.BASE64_DECODE(UTL_RAW.CAST_TO_RAW(InBase64Char)));
ELSE
-- Remove all NEW_LINE from base64 string
DBMS_LOB.CREATETEMPORARY(clob_trim, TRUE);
LOOP
EXIT WHEN read_offset > ClobLen;
stringBuffer := REPLACE(REPLACE(DBMS_LOB.SUBSTR(InBase64Char, amount, read_offset), CHR(13), NULL), CHR(10), NULL);
DBMS_LOB.WRITEAPPEND(clob_trim, LENGTH(stringBuffer), stringBuffer);
read_offset := read_offset + amount;
END LOOP;
read_offset := 1;
ClobLen := DBMS_LOB.GETLENGTH(clob_trim);
DBMS_LOB.CREATETEMPORARY(res, TRUE);
LOOP
EXIT WHEN read_offset > ClobLen;
buffer := UTL_ENCODE.BASE64_DECODE(UTL_RAW.CAST_TO_RAW(DBMS_LOB.SUBSTR(clob_trim, amount, read_offset)));
DBMS_LOB.WRITEAPPEND(res, DBMS_LOB.GETLENGTH(buffer), buffer);
read_offset := read_offset + amount;
END LOOP;
DBMS_LOB.FREETEMPORARY(clob_trim);
END IF;
RETURN res;
END DecodeBASE64;
您可以在互联网上找到许多在线Base64解码器/编码器,您可以在其中验证您的程序。