O
O
Oleg Petrov2018-11-29 10:37:55
Python
Oleg Petrov, 2018-11-29 10:37:55

How to write a connection check code, and if the connection is closed, then try to reconnect to the database?

During the grabber operation, the server unexpectedly closed the connection with it

spoiler
Traceback (most recent call last):
File "C:/Users/Administrator/PycharmProjects/crypto/price_vs4_history.py", line 419, in save_history
self.cur.execute(self.history_insert,t)
psycopg2.OperationalError: server closed the connection unexpectedly
This probably means the server terminated abnormally
before or while processing the request.
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:/Users/Administrator/PycharmProjects/crypto/price_vs4_history.py", line 474, in
run_grabber('01-06-2016')
File "C:/Users/Administrator/PycharmProjects/crypto/price_vs4_history.py", line 466, in run_gecko_grabber
db.save_history(cg.coins[c],dt)
File "C:/Users/Administrator/PycharmProjects/crypto/price_vs4_history.py", line 423, in save_history
self.conn.rollback()
psycopg2.InterfaceError: connection already closed

As I understand it, before any saving to the database, you need to check the connection with it?
Or is it better to make an Exception, and if we go into it, then reconnect to the database again so that the program does not crash?
How is a connection checked?
The class is responsible for connecting to the database
class DBController:
    def __init__(self,database=database, user=user, password=password, host=host, port=port):
        self.conn=psycopg2.connect(database=database,user=user,password=password,host=host,port=port)
        self.cur=self.conn.cursor()

I have added the Reconnect function
def reconnect(self):
   self.conn=psycopg2.connect(database=database,user=user,password=password,host=host,port=port)
   self.cur=self.conn.cursor()

And then on save
except Exception:
     # Тут должен быть цикл со проверкой статуса текущего подключения, но как его сделать?
     #sleep(1)
     #While status ='подключения нет' :
          reconnect()

upd: Googled that Psycopg2 does not provide such information and needs to be done somehow through a request

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Shitskov, 2018-11-29
@Zarom

The Pythonic way is "ask forgiveness not permission".
So try. An exception fell out - process it.
The only thing is probably worth calling reconnect() a limited number of times and at least pausing between attempts.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question