【问题标题】:Return text from Oracle blob column from Oracle database using python使用python从Oracle数据库的Oracle blob列返回文本
【发布时间】:2019-08-14 10:23:22
【问题描述】:

我有这段代码可以从我的数据库的 blob 列中获取文本:

import cx_Oracle
ip = 'your host'
port = 1521
SID = 'ORCL'
USER = 'user'
PASSWORD = 'password'
dsn_tns = cx_Oracle.makedsn(ip, port, SID)


dsn = cx_Oracle.makedsn(ip, port, SID)
orcl = cx_Oracle.connect(USER + '/' + PASSWORD + '@' + dsn)
curs = orcl.cursor()
sql = """SELECT blob_column from table"""
curs.execute(sql)
rows = curs.fetchall()


for x in rows:
   list_ = list(x)
   print(x[0].read)

但是当我用 for 打印时,我得到了这个结果:

<built-in method read of cx_Oracle.LOB object at 0x0547EAE8>
<built-in method read of cx_Oracle.LOB object at 0x0547EAD0>
<built-in method read of cx_Oracle.LOB object at 0x0711D770>

如何从我的 blob 列返回文本?

【问题讨论】:

标签: python python-3.x oracle python-2.7


【解决方案1】:

对于适合内存的 LOBS,您可能会发现将它们作为字符串或字节读取要快得多,请参阅 https://cx-oracle.readthedocs.io/en/latest/user_guide/lob_data.html

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)

idVal = 1
textData = "The quick brown fox jumps over the lazy dog"
bytesData = b"Some binary data"
cursor.execute("insert into lob_tbl (id, c, b) values (:1, :2, :3)",
        [idVal, textData, bytesData])

connection.outputtypehandler = OutputTypeHandler
cursor.execute("select c, b from lob_tbl where id = :1", [idVal])
clobData, blobData = cursor.fetchone()
print("CLOB length:", len(clobData))
print("CLOB data:", clobData)
print("BLOB length:", len(blobData))
print("BLOB data:", blobData)

【讨论】:

    【解决方案2】:

    知道了!

    wkt = rows[0][0].read() # This works for me!
    print(wkt.decode("utf-16")) #And my text back with utf-16 so i had to decode
    orcl.close() 
    

    【讨论】:

      猜你喜欢
      • 2019-01-22
      • 2014-10-02
      • 1970-01-01
      • 2011-09-04
      • 2010-10-06
      • 2014-04-24
      • 2012-01-25
      • 2021-12-29
      • 2014-10-11
      相关资源
      最近更新 更多