数据库
首页 > 数据库> > 如何使用Python将BLOB插入Oracle?

如何使用Python将BLOB插入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.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()并在以后进行更新?在插入之前计算BLOB的大小是否有必要/有益?

解决方法:

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

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

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

标签:python,oracle,blob,cx-oracle
来源: https://codeday.me/bug/20191003/1849482.html