Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if pyodbc connection is open or closed

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?

like image 873
cammil Avatar asked Jun 01 '12 09:06

cammil


People also ask

Does Pyodbc close connection?

According to pyodbc documentation, connections to the SQL server are not closed by default. Some database drivers do not close connections when close() is called in order to save round-trips to the server.

What is cursor in Pyodbc?

wiki. Cursors represent a database cursor (and map to ODBC HSTMTs), which is used to manage the context of a fetch operation. Cursors created from the same connection are not isolated, i.e., any changes done to the database by a cursor are immediately visible by the other cursors.


1 Answers

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
like image 76
Aaron Digulla Avatar answered Sep 20 '22 13:09

Aaron Digulla