How to check status of long lasting ibm_db connection in python

Question:

I’m developing and API that reads data from DB2 and returns corresponding result (using Flask on Python). 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. And that is exactly what I can’t do because I can’t find a function or method that return connection status. 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?

Asked By: Eyyafyadlayokydl

||

Answers:

At python level there is bool ibm_db.active(IBM_DBConnection connection) method which returns the True or False.

You can also run a watchdog query periodically.

Did you investigate the pconnect() method for your use case, it may be more appropriate.?

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.

Answered By: mao

Do this….

try:
    ibm_db.close(conn)
    print('Disconnected')
except:
    print('Error Still connected')
Answered By: Shawna Hobbs
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.