13

I often get this error: ProgrammingError: The cursor's connection has been closed.

Is there a way to check whether the connection I am using has been closed before I attempt to execute a query?

I'm thinking of writing a wrapper to execute queries. First it would check whether the connection is closed, if it is, it would reconnect. Is this an advisable way of doing this?

cammil
  • 9,499
  • 15
  • 55
  • 89

3 Answers3

7

The wrapper is a good idea but I don't know any API to reliably check whether the connection is closed or not.

So the solution would be something along these lines:

for retry in range(3):
    try:
        ... execute query ...
        return # Stop on success
    except e:
        if is_connection_broken_error(e):
             reconnect()
             continue
        raise

raise # throw if the retry fails too often
Aaron Digulla
  • 321,842
  • 108
  • 597
  • 820
5

Another option would be to check if you can get a cursor (many times that's what you want from a connection anyway) and re-initialize the connection otherwise. It will look something like this:

try:
    cursor = conn.cursor()
except e:
    if e.__class__ == pyodbc.ProgrammingError:        
        conn == reinit()
        cursor = conn.cursor()
lribinik
  • 169
  • 2
  • 10
  • 2
    this is not a good idea. pyodbc.ProgrammingError is raised in a lot of situation. Using this you will eat lots of important error messages. – Jamie Marshall Jan 21 '19 at 23:48
2

You can also do duck typing. Use what you need and catch the exception. 99% of the time it is likely to be OK.

Suat Atan PhD
  • 1,152
  • 13
  • 27
Diego Navarro
  • 9,316
  • 3
  • 26
  • 33