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

发布于 2024-12-23 04:32:20 字数 649 浏览 1 评论 0原文

我有这样的代码:

    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:句柄无效!

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

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

软糯酥胸 2024-12-30 04:32:20

我发现在使用 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

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
携君以终年 2024-12-30 04:32:20

想通了。我必须做这样的事情:

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

Figured it out. I have to do something like this:

curs.execute(sql)        
for row in curs:
    print row[0].read()
苍暮颜 2024-12-30 04:32:20

我在稍微不同的环境中遇到了同样的问题。我需要查询一个+27000行的表,结果发现cx_Oracle在一段时间后切断了与数据库的连接。

当与数据库的连接打开时,您可以使用 cx_Oracle.Lob 对象的 read() 方法将其转换为字符串。但是,如果查询带来的表太大,它将无法工作,因为连接将在某个时刻停止,并且当您想要从查询中读取结果时,您将在 cx_Oracle 对象上出现错误。

我尝试了很多事情,比如设置
connection.callTimeout = 0(根据文档,这意味着它将无限期地等待),使用 fetchall() ,然后将结果放在数据帧或 numpy 数组上,但我永远无法读取 cx_Oracle.Lob 对象。

如果我尝试使用 pandas.DataFrame.read_sql(query, connection) 运行查询,数据帧将包含连接关闭的 cx_Oracle.Lob 对象,从而使它们无用。 (同样,只有当表非常大时才会发生这种情况)

最后,我找到了一种通过立即查询和创建 csv 文件来解决这个问题的方法,尽管我知道这并不理想。

def csv_from_sql(sql: str, path: str="dataframe.csv") -> bool:
try: 
    with cx_Oracle.connect(config.username, config.password, config.database, encoding=config.encoding) as connection:
        connection.callTimeout = 0
        data = pd.read_sql(sql, con=connection)
        data.to_csv(path)
        print("FILE CREATED")
except cx_Oracle.Error as error: 
    print(error)
    return False
finally: 
    print("PROCESS ENDED\n")
    return True

def make_query(sql: str, path: str="dataframe.csv") -> pd.DataFrame:
if csv_from_sql(sql, path):
    dataframe = pd.read_csv("dataframe.csv")
    return dataframe
return pd.DataFrame()

这花了很长时间(大约 4 到 5 分钟)才带来了我的 +27000 行表,但当其他一切都不起作用时它就起作用了。

如果有人知道更好的方法,这对我也会有帮助。

I had the same problem with in a slightly different context. I needed to query a +27000 rows table and it turns out that cx_Oracle cuts the connection to the DB after a while.

While a connection to the db is open, you can use the read() method of the cx_Oracle.Lob object to transform it into a string. But if the query brings a table that is too big, it won´t work because the connection will stop at some point and when you want to read the results from the query you´ll gt an error on the cx_Oracle objects.

I tried many things, like setting
connection.callTimeout = 0 (according to documentation, this means it would wait indefinetly), using fetchall() and then putting the results on a dataframe or numpy array but I could never read the cx_Oracle.Lob objects.

If I try to run the query using pandas.DataFrame.read_sql(query, connection) The dataframe would contain cx_Oracle.Lob objects with the connection closed, making them useless. (Again this only happens if the table is very big)

In the end I found a way of getting around this by querying and creating a csv file inmediatlely after, even though I know it´s not ideal.

def csv_from_sql(sql: str, path: str="dataframe.csv") -> bool:
try: 
    with cx_Oracle.connect(config.username, config.password, config.database, encoding=config.encoding) as connection:
        connection.callTimeout = 0
        data = pd.read_sql(sql, con=connection)
        data.to_csv(path)
        print("FILE CREATED")
except cx_Oracle.Error as error: 
    print(error)
    return False
finally: 
    print("PROCESS ENDED\n")
    return True

def make_query(sql: str, path: str="dataframe.csv") -> pd.DataFrame:
if csv_from_sql(sql, path):
    dataframe = pd.read_csv("dataframe.csv")
    return dataframe
return pd.DataFrame()

This took a long time (about 4 to 5 minutes) to bring my +27000-rows table, but it worked when everything else didn´t.

If anyone knows a better way, it would be helpful for me too.

亣腦蒛氧 2024-12-30 04:32:20

你基本上必须循环遍历 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_)

You basically have to loop through the fetchall object

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_)
思念绕指尖 2024-12-30 04:32:20

for循环中应该有一个额外的逗号,请参见下面的代码,我在for循环中的x后面提供了一个额外的逗号。

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:
    print(x)

There should be an extra comma in the for loop, see in below code, i have supplied an extra comma after x in for loop.

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:
    print(x)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文