Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auto reconnect postgresq database

I have the following code:

import psycopg2
conn = psycopg2.connect(database="****", user="postgres", password="*****", host="localhost", port="5432")
print ("Opened database successfully")
cur = conn.cursor()
cur.execute('''select * from xyz''')
print ("Table created successfully")
conn.commit()
conn.close()

Like this i have some 50 -60 complex queries, but problem is some times the postgre sql Database throws the below error

Traceback (most recent call last):
  File "C:/Users/ruw2/Desktop/SQL.py", line 87, in <module>
    cur.execute('''select * from xyz;''')
psycopg2.DatabaseError: server conn crashed?
server closed the connection unexpectedly. 
This probably means the server terminated abnormally before or while processing the request.

Looks like the connection is lost, how can i auto connect the Postgre database Appreciate your help

like image 524
iahmed Avatar asked Feb 22 '17 07:02

iahmed


People also ask

What is Createdb in PostgreSQL?

createdb creates a new PostgreSQL database. Normally, the database user who executes this command becomes the owner of the new database. However, a different owner can be specified via the -O option, if the executing user has appropriate privileges. createdb is a wrapper around the SQL command CREATE DATABASE .

What is Pg_ctl in PostgreSQL?

pg_ctl is a utility for initializing a PostgreSQL database cluster, starting, stopping, or restarting the PostgreSQL database server (postgres), or displaying the status of a running server.


1 Answers

I would rely on decorators - retry and reconnect:

import psycopg2
from tenacity import retry, wait_exponential, stop_after_attempt
from typing import Callable

def reconnect(f: Callable):
    def wrapper(storage: DbStorage, *args, **kwargs):
        if not storage.connected():
            storage.connect()

        try:
            return f(storage, *args, **kwargs)
        except psycopg2.Error:
            storage.close()
            raise

    return wrapper


class DbStorage:

    def __init__(self, conn: string):
        self._conn: string = conn
        self._connection = None

    def connected(self) -> bool:
        return self._connection and self._connection.closed == 0

    def connect(self):
        self.close()
        self._connection = psycopg2.connect(self._conn)

    def close(self):
        if self.connected():
            # noinspection PyBroadException
            try:
                self._connection.close()
            except Exception:
                pass

        self._connection = None

    @retry(stop=stop_after_attempt(3), wait=wait_exponential())
    @reconnect
    def get_data(self): # pass here required params to get data from DB
        # ..
        cur = self._connection.cursor()
        cur.execute('''select * from xyz''')
        # ..
like image 200
vladimir Avatar answered Sep 19 '22 17:09

vladimir