#!/usr/bin/python3

import psycopg2 as pg2

def main():
  try:
    # Connect to database 'assignment1' with user 'user' and password 'pw'.
    connection = pg2.connect(
      "user='user' password='pw' host='localhost' dbname='assignment1'")
  except:
    print("Unable to establish a connection to {}".format('assignment1'))
  
  # Retrieve a so-called cursor in order to interact with the database.
  cursor = connection.cursor()

  try:
    # Send a simple SELECT query to the database.
    cursor.execute("""SELECT * FROM names WHERE primaryName = 'Christian Bale'""")

    # Retrieve the entire result of the query.
    # cursor.fetchone() would retrieve only the first tuple of the result.
    records = cursor.fetchall()

    # Print the retrieved result.
    for record in records:
      print("{}".format(record))
  except:
    print("Unable to execute simple SELECT query.")
  finally: # The finally-branch is always executed (independently of an exception).
    if cursor is not None:
      cursor.close() # Close the cursor.

    if connection is not None:
      connection.close() # Close the connection.

if __name__ == "__main__":
  main()