我在下面有一些代码,它查询数据库并提取 BLOB。我想将此 BLOB 资料保存为档案,但是我无法这样做。我做了一些研究并尝试了各种示例代码,但似乎没有任何效果。
import cx_Oracle
import db_config
con = cx_Oracle.connect(db_config.user, db_config.pw, db_config.dsn)
cur = con.cursor()
def writeTofile(data, filename):
print(data)
print(filename)
with open(filename, "wb") as file:
file.write(data)
print("Stored blob data into: ", filename, "\n")
def output_type_handler(cursor, name, default_type, size, precision, scale):
if default_type == cx_Oracle.DB_TYPE_CLOB:
return cursor.var(cx_Oracle.DB_TYPE_LONG, arraysize=cursor.arraysize)
if default_type == cx_Oracle.DB_TYPE_BLOB:
return cursor.var(cx_Oracle.DB_TYPE_LONG_RAW, arraysize=cursor.arraysize)
con.outputtypehandler = output_type_handler
print("Querying data...")
cur.execute("select payload from table where id=101")
(blob_data) = cur.fetchone()
print("BLOB length:", len(blob_data))
print("BLOB data:", blob_data)
payload = blob_data
trigger = "C:\\Temp\\Training\\Python\\trigger.bin"
print(trigger)
writeTofile(payload, trigger)
我得到的回复如下:
Enter password for DataBase:
Querying data...
BLOB length: 1
BLOB data: (b'5468616e6b7320666f722074616b696e67207468652074696d6520746f2068656c702c20697473206d756368206170726963617465642e',)
C:\Temp\Training\Python\trigger.bin
(b'5468616e6b7320666f722074616b696e67207468652074696d6520746f2068656c702c20697473206d756368206170726963617465642e',)
C:\Temp\Training\Python\trigger.bin
Traceback (most recent call last):
File "C:\Temp\Training\Python\python-cx_Oracle-main\samples\tutorial\read_blob3.py", line 39, in <module>
writeTofile(payload, trigger)
File "C:\Temp\Training\Python\python-cx_Oracle-main\samples\tutorial\read_blob3.py", line 20, in writeTofile
file.write(data)
TypeError: a bytes-like object is required, not 'tuple'
我真的不明白为什么提到writeTofile(payload, trigger)因为我在 wrtietofile 函式中的打印陈述句显示资料已传递,我错过了什么?
我以为我必须将资料转换为字节阵列,但这给了我一个不同的错误;
TypeError: 'bytes' object cannot be interpreted as an integer
任何帮助都非常受欢迎。
uj5u.com热心网友回复:
型别payload
是元组,你需要呼叫函式为,
writeTofile(payload[0], trigger)
uj5u.com热心网友回复:
您正在尝试将元组写入具有以下内容的档案:file.write(data)
。您的数据库查询回传一个具有一个结果的元组。您必须像这样提取这个结果,例如:(blob_data) = cur.fetchone()[0]
. 或者,您可以像这样在 write 函式中回圈遍历结果:
with open(filename, "wb") as file:
for datapoint in data:
file.write(datapoint b"\n")
当您有多个要写入档案的资料点时,这也将起作用。
0 评论