-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpostgres.py
41 lines (37 loc) · 974 Bytes
/
postgres.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import os
import psycopg2
from dotenv import load_dotenv
load_dotenv()
def get_connection():
try:
conn = psycopg2.connect(
database=os.getenv('POSTGRES_DBNAME'),
user=os.getenv('POSTGRES_USER'),
password=os.getenv('POSTGRES_PASSWORD'),
host=os.getenv('POSTGRES_HOST'),
port=5432,
)
if conn:
return conn
except:
print("Connection to the PostgreSQL encountered and error.")
os._exit(1)
def consultar_db(conn, sql):
cur = conn.cursor()
cur.execute(sql)
recset = cur.fetchall()
registros = []
for rec in recset:
registros.append(rec)
return registros
def run_db(conn, sql):
cur = conn.cursor()
try:
cur.execute(sql)
conn.commit()
except (Exception, psycopg2.DatabaseError) as error:
print("Error: %s" % error)
conn.rollback()
cur.close()
return 1
cur.close()