【问题标题】:Blob data from Oracle to text file using python使用 python 从 Oracle 到文本文件的 Blob 数据
【发布时间】:2019-01-22 21:16:19
【问题描述】:

我一直在尝试使用 Python 将 blob 数据从 oracle 获取到文本文件中。我在其他任何链接上都找不到答案。

下面是我的代码:

sql_string = """select 
   event_id
   ,blob_length
   ,blob field
from table"""

  cur.execute(sql_string)
    path = "P:/Folders/"

    for row in cur:
        filename = path +  "notes_" + str(row[0]) + "_" + str(row[1]) + ".txt"      
        f = codecs.open(filename, encoding='utf-8', mode='wb+')
        f.write(row[2])
        f.close()

我收到以下错误

TypeError: utf_8_encode() argument 1 must be str, not cx_Oracle.LOB

我尝试了其他一些方法,但问题是即使是我见过的其他方法也只能处理字符串而不是 blob。

【问题讨论】:

  • 您必须将 LOB 数据读入str。试试row[2].read()

标签: python oracle blobs


【解决方案1】:

你必须使用cx_oracle.LOB.read()方法来获取LOB对象的内容:

f.write(row[2].read())

【讨论】:

  • 非常感谢!!
【解决方案2】:

实现了@blhsing 的建议并且效果很好

    for row in cur:
        filename = path +  "notes_" + str(row[0]) + "_" + str(row[1]) + ".txt"      
        print(row[2].read())
        f = open(filename, "wb")
        f.write(row[2].read())
        f.close()        

【讨论】:

    【解决方案3】:

    如果您的 LOB 足够小以适合内存,如果您将 BLOB 提取为 LONG_BINARY(并对 CLOB 使用 LONG_STRING),您将获得更好的性能:

    def OutputTypeHandler(cursor, name, defaultType, size, precision, scale):
        if defaultType == cx_Oracle.CLOB:
            return cursor.var(cx_Oracle.LONG_STRING, arraysize = cursor.arraysize)
        if defaultType == cx_Oracle.BLOB:
            return cursor.var(cx_Oracle.LONG_BINARY, arraysize = cursor.arraysize)
    

    请参阅https://github.com/oracle/python-cx_Oracle/blob/master/samples/ReturnLobsAsStrings.py 上的 cx_Oracle 示例

    【讨论】:

    • 谢谢克里斯托弗。我只是在阅读 cmets,它说这种方法需要连续内存,因此不适用于非常大的 LOB。而且我已经面临大斑点的问题。而且我正在尝试写入文本文件,以便我可以解压缩当前无法处理数据帧或文本文件的完整 blob。 stackoverflow.com/questions/51922686/… 任何帮助/建议都会很棒!!
    猜你喜欢
    • 1970-01-01
    • 2013-12-04
    • 2016-06-14
    • 2020-11-22
    • 2021-10-02
    • 1970-01-01
    • 2021-07-17
    • 2014-10-02
    • 2018-05-10
    相关资源
    最近更新 更多