import configparser import psycopg2 configfile = configparser.ConfigParser() configfile.read('config.ini') config = configfile['database'] print("Connecting to database...") with psycopg2.connect( database=config['name'], user=config['user'], password=config['password'], host=config['host'], port=config['port'] ) as connection: print("Connected to %s:%s (%s) as %s" % (config['host'], config['port'], config['name'], config['user'])) print("Querying PostgreSQL version...") with connection.cursor() as cursor: query = "SELECT version();" cursor.execute(query) print("Results:") rows = cursor.fetchall() for row in rows: print("->", *row) # Si estuvieramos modificando datos con # cursor.execute(...) # sería necesario hacer commit de los cambios: # cursor.commit() # Al manejar la conexión y el cursor mediante contextos, # estos se cierran automáticamente. De otro modo, lo # correcto habría sido hacer cursor.close() y connection.close() print("Done!")