import psycopg2 from contextlib import closing import sys import json database = "daily_report_test" user = "reporter" password = "reporter" host = "localhost" port = 5432 sql_query = "select failed_count from youtube_trending_charts_failed_count where id=1;" # grab sql data with closing connection after it def fetch_sql_data(sql_req): with closing(psycopg2.connect(database=database, user=user, password=password, host=host, port=port)) as connection: with connection.cursor() as cursor: cursor.execute(sql_req) columns = cursor.description rows = cursor.fetchall() for row in rows: failure_count = row[0] return failure_count if __name__ == '__main__': print (fetch_sql_data(sql_query))