如何在Python中读取cx_Oracle.LOB数据?

2024-04-19 07:50:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这个密码:

    dsn = cx_Oracle.makedsn(hostname, port, sid)
    orcl = cx_Oracle.connect(username + '/' + password + '@' + dsn)
    curs = orcl.cursor()
    sql = "select TEMPLATE from my_table where id ='6'"
    curs.execute(sql)
    rows = curs.fetchall()
    print rows
    template = rows[0][0]
    orcl.close()
    print template.read()

当我做print rows时,我得到:

[(<cx_Oracle.LOB object at 0x0000000001D49990>,)]

但是,当我执行print template.read()时,会出现以下错误:

cx_Oracle.DatabaseError: Invalid handle!

如何获取和读取这些数据?谢谢。


Tags: 密码readsqlporttemplatehostnamerowsoracle
3条回答

我发现在使用cx_Oracle.LOB.read()方法之前关闭与Oracle的连接时会发生这种情况。

orcl = cx_Oracle.connect(usrpass+'@'+dbase)
c = orcl.cursor()
c.execute(sq)
dane =  c.fetchall()

orcl.close() # before reading LOB to str

wkt = dane[0][0].read()

我得到:数据库错误:无效句柄!
但以下代码有效:

orcl = cx_Oracle.connect(usrpass+'@'+dbase)
c = orcl.cursor()
c.execute(sq)
dane =  c.fetchall()

wkt = dane[0][0].read()

orcl.close() # after reading LOB to str

基本上你必须循环遍历fetchall对象

dsn = cx_Oracle.makedsn(hostname, port, sid)
orcl = cx_Oracle.connect(username + '/' + password + '@' + dsn)
curs = orcl.cursor()
sql = "select TEMPLATE from my_table where id ='6'"
curs.execute(sql)
rows = curs.fetchall()
for x in rows:
   list_ = list(x)
   print(list_)

明白了。我必须这样做:

curs.execute(sql)        
for row in curs:
    print row[0].read()

相关问题 更多 >