How to verify pyodbc database connection is still open?

I have Python v3.12.1 on Windows 10.

In the beginning of my program I open a connection to a pyodbc database and store the connection in an options class variable. It is stored in options.dbconn. This allows me to have one connection and reuse it in many functions, putting less stress on the database server. I have a db connection timeout set to 900 seconds.

The connection is initially opened because some functions are using that options.dbconn to read more records. But at some point I’m getting an error like “Tried to use closed connection”.

Somewhere in my program the connection is getting closed.

if I do this in the debugger p options.dbconn it doesn’t tell me if the db connection is open, it just says something like <pyodbc.Connection object at 0x00000186767DC1D0>.

How do I verify in the pdb debugger that the connection is still open?

Thank you.

p.s. I’m assuming the database timeout value is used when executing a single query. I did not think it would close the object after 900 seconds it is idle.

EDIT: Oh dear. If I do

conn = pyodbc.conn(options.connstring)
options.dbconn = conn

Then later in the function I do

conn.close()

Does that also close options.dbconn?

Is options.dbconn = conn just copying a pointer, not the actual object, like a dictionary does?

yes, assignment in python does not copy, just adds another name to the object.
See copy — Shallow and deep copy operations
Besides, copying a database connection probably would not work anyway, there is a lot of state involved (transactions, cursors, sockets and so on)

1 Like

Confirmed. By finding an extra conn.close() in my function, and removing it, it all works fine now.

I will need to remember that detail.

1 Like