import psycopg2 try: # Establish the connection conn = psycopg2.connect( user="sql-ledger", password="a123s", host="localhost", port="5432", database="testdb" ) # Create a cursor object cursor = conn.cursor() # Execute a query cursor.execute("SELECT version();") # Fetch the result record = cursor.fetchone() print("You are connected to - ", record, "\n") except (Exception, psycopg2.Error) as error: print("Error while connecting to PostgreSQL", error) finally: # Closing database connection if conn: cursor.close() conn.close() print("PostgreSQL connection is closed")