Last active
January 26, 2023 17:59
-
-
Save fabiuxx/a9f68171b3234f14f65b143597c32bbf to your computer and use it in GitHub Desktop.
Script que utiliza psycopg2 para conectarse a una base de datos postgres.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import traceback | |
import munch | |
import psycopg2 | |
import sys | |
DEBUG_QUERYS = False | |
def row_to_dict(cursor, row): | |
x = {} | |
for key, col in enumerate(cursor.description): | |
x[col[0]] = row[key] | |
return x | |
def dict_to_object(d): | |
return munch.munchify(d) | |
def get_connection(**kwargs): | |
host = kwargs['host'] | |
port = kwargs['port'] | |
dbname = kwargs['dbname'] | |
user = kwargs['user'] | |
password = kwargs['password'] | |
conn_string = "host='%s' port='%s' dbname='%s' user='%s' password='%s'" % (host, port, dbname, user, password) | |
return psycopg2.connect(conn_string) | |
def fetch_all(conn, query): | |
cursor = conn.cursor() | |
try: | |
print(query) if DEBUG_QUERYS else None | |
cursor.execute(query) | |
rows = cursor.fetchall() | |
D = [row_to_dict(cursor, row) for row in rows] | |
D = [dict_to_object(d) for d in D] | |
return D | |
except: | |
traceback.print_exc() | |
return [] | |
finally: | |
cursor.close() | |
def fetch_first(conn, query): | |
D = fetch_all(conn, query) | |
if len(D) != 0: | |
return D[0] | |
else: | |
return None | |
if __name__ == '__main__': | |
conn = get_connection(host='x.x.x.x', port='xxxx', dbname='xxx', user='xxx', password='xxx') | |
if conn is None: | |
print('No se pudo conectar a la base de datos') | |
exit(-1) | |
conn.autocommit = False | |
try: | |
# Realizar trabajo. | |
conn.commit() | |
except: | |
# Error. | |
sys.stderr.write('rollback ...') | |
traceback.print_exc() | |
conn.rollback() | |
finally: | |
conn.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment