Convert Oracle BLOB to String: Methods & Code
There are several methods to convert an Oracle BLOB to a string.
- Utilize Oracle’s built-in package: You can use the functions within the DBMS_LOB package to convert a BLOB to a string. For example, you can use the DBMS_LOB.SUBSTR function to extract a portion of the BLOB and convert it to a string. Below is an example code:
DECLARE
l_blob BLOB;
l_clob CLOB;
l_offset NUMBER := 1;
l_amount NUMBER := 32767;
l_buffer VARCHAR2(32767);
BEGIN
-- 从表中获取BLOB数据
SELECT blob_column INTO l_blob FROM my_table WHERE id = 1;
-- 将BLOB转换为CLOB
DBMS_LOB.CREATETEMPORARY(l_clob, TRUE);
DBMS_LOB.CONVERTTOCLOB(l_clob, l_blob, l_amount, l_offset, 1);
-- 逐步读取CLOB并将其转换为字符串
LOOP
EXIT WHEN l_offset > DBMS_LOB.GETLENGTH(l_clob);
DBMS_LOB.READ(l_clob, l_amount, l_offset, l_buffer);
-- 在此处可以对字符串进行处理
DBMS_OUTPUT.PUT_LINE(l_buffer);
l_offset := l_offset + l_amount;
END LOOP;
-- 释放CLOB
DBMS_LOB.FREETEMPORARY(l_clob);
END;
- You can convert a BLOB to a string using PL/SQL code. Here is an example code:
DECLARE
l_blob BLOB;
l_clob CLOB;
l_offset NUMBER := 1;
l_amount NUMBER := 32767;
l_buffer VARCHAR2(32767);
BEGIN
-- 从表中获取BLOB数据
SELECT blob_column INTO l_blob FROM my_table WHERE id = 1;
-- 将BLOB逐步转换为CLOB
WHILE l_offset <= DBMS_LOB.GETLENGTH(l_blob) LOOP
l_buffer := UTL_RAW.CAST_TO_VARCHAR2(DBMS_LOB.SUBSTR(l_blob, l_amount, l_offset));
-- 在此处可以对字符串进行处理
DBMS_OUTPUT.PUT_LINE(l_buffer);
l_offset := l_offset + l_amount;
END LOOP;
END;
- External tools can be used to export BLOB data, such as PL/SQL Developer, and save it as a file. The file can then be opened with a text editor or other tools, and the contents copied into a string. This method is relatively simple, but requires the use of additional tools.