如何使用Python将BLOB插入Oracle?

如何使用Python将BLOB插入Oracle?,python,oracle,blob,cx-oracle,Python,Oracle,Blob,Cx Oracle,我正在尝试使用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

我正在尝试使用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()

插入一个
空的\u BLOB()
并稍后执行
更新如何?是否有必要/有益于在插入之前计算BLOB的大小?

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

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

插入一个空的_blob()值并返回LOB定位器以供以后更新比创建一个临时LOB并插入它(就像您在代码中所做的那样)要快,但是直接插入数据要快得多

谢谢你的解释。那么,也不需要为cursor.var指定BLOB的大小?不客气。不,不需要给出水滴的大小。