Search code examples
pythonpostgresqlpsycopg2

How should I do exception handling in my database python code for no data fetched from server or connection time out


psycopg2.DatabaseError: could not receive data from server: Connection timed out


Solution

  • you can use this code in your :

     def retrieve_data(db, table_name):
        try:
            comm ="SELECT * FROM {};".format(table_name)
            with db.connect() as conn:
                column_of_sql_table = conn.execute(comm).fetchall()
            return pd.DataFrame(column_of_sql_table)
    
        except Exception as e:
            print(e)
            return pd.DataFrame()
    
    df = retrieve_data(db, table_name)
    if not df.empty :
        < do what ever you want>
    else: 
        < rise error>