代码之家  ›  专栏  ›  技术社区  ›  wolφi

使用python将clob插入oracle时,如何调用dbms_crypto.hash?

  •  0
  • wolφi  · 技术社区  · 6 年前

    我在甲骨文中存储clobs。为了加快查找相同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)

    1 回复  |  直到 6 年前
        1
  •  1
  •   Luke Woodward    6 年前

    这对我很有用,诚然与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 你的不工作代码:我的11gxe数据库给了我错误 ORA-24816: Expanded non LONG bind data supplied after actual LONG or LOB column 相反。