Blob data from Oracle to text file using python

天涯浪子 提交于 2019-12-24 08:35:27

问题


I have been trying to get the blob data from oracle into a text file using Python. I couldn't find the answer on any of the other links.

Below is my code :

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()

I get the below error

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

I have tried a few other ways but the problem is that even other approaches that I've seen only handle strings and not blobs.


回答1:


You have to use the cx_oracle.LOB.read() method to get the content of the LOB object:

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



回答2:


Implemented what @blhsing suggested and it worked out perfectly

    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:


If your LOBs are small enough to fit in memory you'll get better performance if you fetch BLOBs as LONG_BINARY (and use LONG_STRING for CLOBs):

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)

See the cx_Oracle example at https://github.com/oracle/python-cx_Oracle/blob/master/samples/ReturnLobsAsStrings.py



来源:https://stackoverflow.com/questions/51868112/blob-data-from-oracle-to-text-file-using-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!