简体   繁体   English

如何检查 python 中持久 ibm_db 连接的状态

[英]How to check status of long lasting ibm_db connection in python

I'm developing and API that reads data from DB2 and returns corresponding result (using Flask on Python).我正在开发 API 从 DB2 读取数据并返回相应的结果(在 Python 上使用 Flask)。 Initially I had connection open on each API call but since number of connections per second is growing I thought it's better to open DB connection once and re-open it only if it closed/failed for any reason.最初,我在每个 API 调用上都打开了连接,但是由于每秒的连接数在增长,我认为最好打开一次 DB 连接并仅在它因任何原因关闭/失败时才重新打开它。 And that is exactly what I can't do because I can't find a function or method that return connection status.这正是我不能做的,因为我找不到 function 或返回连接状态的方法。 I tried:我试过了:

conn = ibm_db.connect(dbname, dbuser, dbpswd)
if conn:
    print('ok')
else:
    print('not ok')
print(conn)

ibm_db.close(conn)
if conn:
    print('ok')
else:
    print('not ok')
print(conn)}

It returned:它返回:

ok
<ibm_db.IBM_DBConnection object at 0xa000000012bd530>
ok
<ibm_db.IBM_DBConnection object at 0xa000000012bd530>

so this definitely doesn't work for closed connection.所以这绝对不适用于封闭连接。 Is there a way to check if previously opened connection is still alive?有没有办法检查以前打开的连接是否仍然存在?

At python level there is bool ibm_db.active(IBM_DBConnection connection) method which returns the True or False.在 python 级别有bool ibm_db.active(IBM_DBConnection connection)方法,它返回 True 或 False。

You can also run a watchdog query periodically.您还可以定期运行看门狗查询。

Did you investigate the pconnect () method for your use case, it may be more appropriate.?您是否针对您的用例调查了pconnect () 方法,它可能更合适。?

Remember that the TCPIP heartbeat on the connection may also expire if the connection is idle for longer than a certain period (for example 2 hours), and the Db2-server may close the connection in this case.请记住,如果连接空闲时间超过特定时间(例如 2 小时),连接上的 TCPIP 心跳也可能会过期,并且 Db2 服务器可能会在这种情况下关闭连接。

Do this....做这个....

try:
    ibm_db.close(conn)
    print('Disconnected')
except:
    print('Error Still connected')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM