Oracle数据库中向BLOB类型字段插入字符串并把插入的BLOB数据转换成字符串显示的方法
首先先在数据库中创建一张表
create table TB_TEST
(
ID NUMBER,
BLB BLOB
)
其次向表中插入一条空数据
insert into tb_test (id,blb) values (1,empty_blob())
最后更改BLOB字段的值
declare
directions BLOB;
amount BINARY_INTEGER;
offset INTEGER;
first_direction VARCHAR2(100);
more_directions VARCHAR2(500);
begin
update set blb = empty_blob() where id = 1; --更新和新增一样要将BLOB字段设置为EMPTY_BLOB()
select blb into directions from tb_test where id = 1 for update; --一定要用for update锁住记录,否则
--DBMS_LOB.OPEN会出错
DBMS_LOB.OPEN(directions, DBMS_LOB.LOB_READWRITE);
first_direction := '这是我的第一个插入blob的数据,测试一下看一下效果如何,是否能够用pl/sql直接插到插入的数据值!';
amount := LENGTHB(first_direction); --number of characters to write
--有中文必须用LENGTHB
offset := 1; --begin writing to the first character of the CLOB
DBMS_LOB.WRITE(directions,
amount,
offset,
UTL_RAW.cast_to_raw(first_direction));
--UTL_RAW.cast_to_raw函数将字符串转换成二进制数
DBMS_LOB.CLOSE(directions);
commit;
end;
把插入的BLOB数据转换成字符串显示的方式是
select id,UTL_RAW.cast_to_varchar2(blb) blb from tb_test t;
这种方式在显示纯文本字符串时显示的是正常的,可当我插入的数据例如是
这种时在查询显示时就会显示为空。作者 sqcjy111