feat: add example python script

This commit is contained in:
2025-12-26 14:18:05 +01:00
parent c234c31b2c
commit a7476ae216
3 changed files with 49 additions and 1 deletions

6
code/config.ini Normal file
View File

@@ -0,0 +1,6 @@
[database]
name = taller_postgres
user = postgres
password = foss
host = localhost
port = 5432

40
code/query_version.py Normal file
View File

@@ -0,0 +1,40 @@
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!")