使用 Python 将 CLOB 插入 Oracle 时如何调用 DBMS_CRYPTO.HASH?

How to call DBMS_CRYPTO.HASH when inserting a CLOB into Oracle with Python?

我在 Oracle 中存储 CLOB。为了加快查找相同的 CLOB,我想引入 CLOB 的哈希值。到目前为止我尝试的是

  1. 插入 CLOB
  2. 根据存储的 clob 更新哈希值。

这怎么能一次完成而不是两次呢?

#!/usr/local/bin/python3
import cx_Oracle

con = cx_Oracle.connect('scott/tiger@localhost:1512/ORCLPDB1', encoding="UTF-8")
cursor = con.cursor()
cursor.execute("CREATE TABLE t (id NUMBER, script CLOB, script_hash RAW(32))")  

my_text = '$'*2**10

statement = "INSERT INTO t (id, script) VALUES (:my_id, :my_clob)"
cursor.execute(statement, (1, my_text))

statement = """
    UPDATE t 
       SET script_hash = DBMS_CRYPTO.HASH(script, 2) 
     WHERE id = :my_id"""
cursor.execute(statement, {'my_id': 1})

con.commit()    
con.close()

这不起作用:

statement = """
   INSERT INTO t (id, script, script_hash) 
   VALUES (:my_id, :my_clob, DBMS_CRYPTO.HASH(:my_clob, 2))"""
cursor.execute(statement, (2, my_text, my_text))

# cx_Oracle.DatabaseError: ORA-01465: invalid hex number

(Oracle 12.2 使用 Python 和 cx_Oracle 6.3)

诚然,这适用于 Oracle 11g XE(和 cx_Oracle 6.3.1):

statement = """
   DECLARE
      l_clob         CLOB   := :my_clob;
   BEGIN
     INSERT INTO t (id, script, script_hash) 
       VALUES (:my_id, l_clob, DBMS_CRYPTO.HASH(l_clob, 2));
   END;"""

cursor.execute(statement, (my_text, 2))

我无法用你的无效代码重现你的错误 ORA-01465: invalid hex number:我的 11g XE 数据库给了我错误 ORA-24816: Expanded non LONG bind data supplied after actual LONG or LOB column