【问题标题】:How to insert a BLOB into Oracle with Python?如何使用 Python 将 BLOB 插入 Oracle?
【发布时间】:2018-11-13 16:52:41
【问题描述】:

我正在尝试使用 cx_Oracle 6.3 将大量 BLOB(每个 2 到 20 MB)插入 Oracle 12。

经过大量的谷歌搜索和实验,我得到了以下代码。我是 Python 新手,想知道:这种方法有效吗?有更快的方法吗?

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

pdf = open('hello.pdf', 'rb')
mem_file = io.BytesIO(pdf.read())
mem_file.seek(0, os.SEEK_END)
file_size = mem_file.tell()

con = cx_Oracle.connect("user", "***", "localhost:1512/ORCLPDB1", encoding="UTF-8")

# create table for this example
con.cursor().execute("CREATE TABLE t (id NUMBER, b BLOB) LOB(b) STORE AS SECUREFILE(COMPRESS)");

# prepare cursor
cursor = con.cursor()
my_blob = cursor.var(cx_Oracle.BLOB, file_size)
my_blob.setvalue(0, mem_file.getvalue())

# execute insert
cursor.execute("INSERT INTO t(id, b) VALUES (:my_id, :my_blob)", (1, my_blob))
con.commit()

con.close()

插入一个EMPTY_BLOB() 然后再做一个UPDATE 怎么样?在插入之前计算 BLOB 的大小是否有必要/有益?

【问题讨论】:

    标签: python oracle blob cx-oracle


    【解决方案1】:

    你可以做一些更简单的事情,这也会相当快。请注意,这种方法仅在您能够将整个文件内容存储在连续内存中并且当前的硬限制为 1 GB 时才有效,即使您有许多 TB 的可用 RAM!

    cursor.execute("insert into t (id, b) values (:my_id, :my_blob)",
            (1, mem_file.getvalue())
    

    插入一个 empty_blob() 值并返回 LOB 定位器以供以后更新比创建一个临时 LOB 并插入它(正如您在代码中所做的那样)更快,但直接插入数据甚至更快!

    【讨论】:

    • 感谢您的精彩解释。那么就不需要给 cursor.var 提供 BLOB 的大小了吗?
    • 不客气。不,不需要给出 BLOB 的大小。
    猜你喜欢
    • 2011-02-01
    • 2016-11-13
    • 1970-01-01
    • 2015-09-12
    • 2019-11-06
    • 2019-11-19
    • 2013-05-03
    • 1970-01-01
    • 2021-08-21
    相关资源
    最近更新 更多