Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I read cx_Oracle.LOB data in Python?

Tags:

I have this code:

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

When I do print rows, I get this:

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

However, when I do print template.read(), I get this error:

cx_Oracle.DatabaseError: Invalid handle!

Do how do I get and read this data? Thanks.

like image 738
Di Zou Avatar asked Dec 27 '11 16:12

Di Zou


People also ask

What is cx_Oracle lob?

There are four types of LOB (large object): BLOB - Binary Large Object, used for storing binary data. cx_Oracle uses the type cx_Oracle. DB_TYPE_BLOB . CLOB - Character Large Object, used for string strings in the database character set format.

What is Python cx_Oracle?

cx_Oracle is a Python extension module that enables access to Oracle Database. It conforms to the Python database API 2.0 specification with a considerable number of additions and a couple of exclusions. cx_Oracle 8.3 was tested with Python versions 3.6 through 3.10.


1 Answers

I've found out that this happens in case when connection to Oracle is closed before the cx_Oracle.LOB.read() method is used.

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

And I get: DatabaseError: Invalid handle!
But the following code works:

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
like image 96
geowrw Avatar answered Nov 11 '22 05:11

geowrw