feat: add example python script
This commit is contained in:
6
code/config.ini
Normal file
6
code/config.ini
Normal file
@@ -0,0 +1,6 @@
|
||||
[database]
|
||||
name = taller_postgres
|
||||
user = postgres
|
||||
password = foss
|
||||
host = localhost
|
||||
port = 5432
|
||||
40
code/query_version.py
Normal file
40
code/query_version.py
Normal 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!")
|
||||
|
||||
Reference in New Issue
Block a user