用python从数据库中阅读blob数据并以.zip格式存储

thtygnil  于 2023-03-21  发布在  Python
关注(0)|答案(2)|浏览(221)

嗨,我试图使用Python从我的Oracle数据库存储Blob数据,并试图将其存储在本地文件夹中。zip格式。所以我现在有两个代码,其中一个运行良好,但只获取一行并将其存储为文件夹中的。zip,但另一个我试图获取多行,不工作,可能我正在做一些基本的错误,但无法弄清楚,所以请帮助我。下面是代码:-
代码1-运行良好,只获取一行并将其存储为.zip文件夹中:-

import cx_Oracle
import numpy as np
import pandas as pd
con = cx_Oracle.connect("OPTDB90", "OPTDB90", "INDLIN2338:1521/OPTEPC1")
cursor = con.cursor()
sql_string = """SELECT F_name, F_released_data FROM epc_project where rownum<5"""
cursor.execute(sql_string)
#Path="C:\Users\adityasi\Desktop\MY Important\QueryGeneratorPytthonFinal\Project\EPCPROJECTS"
row = cursor.fetchone()
blobdata = np.array(row[1].read())
cursor.close()
filename = str(row[0]) + ".zip"
f = open(filename, 'w+b')
binary_format = bytearray(blobdata)
f.write(binary_format)
f.close()

代码2-抛出错误,无法获取多行并将其存储为.zip文件夹中:-

import cx_Oracle
import numpy as np
import pandas as pd
con = cx_Oracle.connect("OPT", "OPT", "INDLIN2338:1521/OPT1")
cursor = con.cursor()
sql_string = """SELECT F_name, F_released_data FROM epc_project where rownum<5"""
cursor.execute(sql_string)
rows = cursor.fetchall()
for row in rows:
        blobdata= np.array(row[1].read())
        cursor.close()
        filename =str(row[0]) + ".zip"
con.close()
f = open(filename, "wb")
binary_format = bytearray(blobdata)
f.write(binary_format)
f.close()

错误:-

blobdata= np.array(row[1].read())
AttributeError: 'str' object has no attribute 'read'

Process finished with exit code 1

请帮帮我谢谢,阿迪亚

mqkwyuun

mqkwyuun1#

我不确定是否需要使用numpy,但在任何情况下,您都有几个选择:
(1)使用输出类型处理程序来确保LOB数据直接以字节的形式返回,而不是以必须调用read()的BLOB的形式返回。有关如何执行此操作的详细信息,请参阅文档。
(2)循环访问游标并分别处理每一行,如下所示:

cursor.execute(sql_string)
for name, data in cursor:
    create_zip_file()
kcwpcxri

kcwpcxri2#

试试这个)
游标=连接游标()
sql_string = 'select id,photo from NEO_V '
行=游标.执行(sql_string)
img_name,img_file = cursor.fetchone()
路径= 'C:\ii\bever_31_005\dataset'
mask =“.jpg”
对于行中的行:

#blobdata= np.array(row[1].read())

filename = f'{path}{str(rows[0])}{mask}'

#print (filename)

offset = 1

num_bytes_in_chunk = 65536

with open(filename, "wb") as f:

    while True:

        data = rows[1].read(offset, num_bytes_in_chunk)

        if data:

            f.write(data)

        if len(data) < num_bytes_in_chunk:

            break

        offset += len(data)

f.close()

连接关闭()

相关问题