【问题标题】:Reading blob data from database by python and store it in .zip format通过python从数据库中读取blob数据并以.zip格式存储
【发布时间】:2020-03-11 12:57:32
【问题描述】:

您好,我正在尝试使用 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

请帮帮我。 谢谢, 阿迪亚

【问题讨论】:

标签: python oracle blob cx-oracle


【解决方案1】:

我不确定是否需要使用 numpy,但在任何情况下,您都有几个选择:

(1) 使用输出类型处理程序来确保 LOB 数据直接作为字节返回,而不是作为必须调用 read() 的 BLOB。有关如何执行此操作的详细信息,请参阅documentation

(2) 遍历游标,分别处理每一行,如:

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

【讨论】:

  • 感谢您的帮助。我试图迭代光标。但出现错误,请参阅更新后的问题说明。
  • 该错误意味着该列已作为字符串返回,因此无需对其调用 read() !
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-02
  • 2020-10-21
  • 1970-01-01
  • 2021-02-22
  • 2021-12-24
相关资源
最近更新 更多