在C#中将Oracle CLOB数据转换为字符串

在C#中将Oracle CLOB数据转换为字符串

问题描述:

我正在尝试运行以下查询,该查询返回C#中的DataTable对象.

I am trying to run the below query which returns a DataTable object in C#.

select TO_CLOB(BLOB) FROM TestBlobData where BSIZE=5000

当我尝试从数据表对象中提取值时,会看到一个垃圾值.

When I try to extract the value out of datatable object, a junk value is seen.

DataTable dataTable = RunQuery(QueryMentionedAbove);
var str = dataTable.Rows[0]["BLOB"].ToString();

当我查看 Str 时,看不到转​​换后的字符串.BLOB实际上是一个JSON字符串.我不能使用TO_CHAR或TO_NCHAR,因为我的Blob大小将大于4000.我的期望是看到将其存储为BLOB的JSON字符串.

When I look at Str , I could not see the converted string. The BLOB is actually a JSON string. I cannot use TO_CHAR or TO_NCHAR because my blob size will be greater than 4000. My expectation is to see the JSON string which I stored it as BLOB.

请帮助我将CLOB转换为C#代码中的字符串.

Please help me in converting the CLOB to string in C# code.

您可以使用该功能(此答案的反方向):

You can use the function (the reverse of this answer):

CREATE FUNCTION blob_to_clob(
  value            IN BLOB,
  charset_id       IN INTEGER DEFAULT DBMS_LOB.DEFAULT_CSID,
  error_on_warning IN NUMBER  DEFAULT 0
) RETURN CLOB
IS
  result       CLOB;
  dest_offset  INTEGER := 1;
  src_offset   INTEGER := 1;
  lang_context INTEGER := DBMS_LOB.DEFAULT_LANG_CTX;
  warning      INTEGER;
  warning_msg  VARCHAR2(50);
BEGIN
  DBMS_LOB.CreateTemporary(
    lob_loc => result,
    cache   => TRUE
  );

  DBMS_LOB.CONVERTTOCLOB(
    dest_lob     => result,
    src_blob     => value,
    amount       => LENGTH( value ),
    dest_offset  => dest_offset,
    src_offset   => src_offset,
    blob_csid    => charset_id,
    lang_context => lang_context,
    warning      => warning
  );
  
  IF warning != DBMS_LOB.NO_WARNING THEN
    IF warning = DBMS_LOB.WARN_INCONVERTIBLE_CHAR THEN
      warning_msg := 'Warning: Inconvertible character.';
    ELSE
      warning_msg := 'Warning: (' || warning || ') during BLOB conversion.';
    END IF;
    
    IF error_on_warning = 0 THEN
      DBMS_OUTPUT.PUT_LINE( warning_msg );
    ELSE
      RAISE_APPLICATION_ERROR(
        -20567, -- random value between -20000 and -20999
        warning_msg
      );
    END IF;
  END IF;

  RETURN result;
END blob_to_clob;
/

然后,如果您具有此答案和数据中的 CLOB_TO_BLOB 函数和数据:/p>

Then, if you have the CLOB_TO_BLOB function from this answer and the data:

CREATE TABLE table_name ( value BLOB );

INSERT INTO table_name (value ) VALUES ( CLOB_TO_BLOB( 'abcdefg' ) );

然后:

SELECT BLOB_TO_CLOB( value ) FROM table_name;

输出:


| BLOB_TO_CLOB(VALUE) |
| :------------------ |
| abcdefg             |

db<>小提琴此处