-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdb_helper.py
More file actions
45 lines (40 loc) · 1.22 KB
/
db_helper.py
File metadata and controls
45 lines (40 loc) · 1.22 KB
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
42
43
44
45
import psycopg2
import pandas as pd
# ======================================================
# CONFIGURACIÓN DB (el candidato debe editar esto)
# ======================================================
DB_HOST = "localhost"
DB_PORT = 5432
DB_NAME = "public"
DB_USER = "postgres"
DB_PASSWORD = "password"
# ======================================================
# CONEXIÓN
# ======================================================
def get_connection():
return psycopg2.connect(
host=DB_HOST,
port=DB_PORT,
user=DB_USER,
password=DB_PASSWORD,
)
# ======================================================
# EJECUCIÓN SQL (CREATE / INSERT / UPDATE / DELETE)
# ======================================================
def execute(sql: str, params=None):
conn = get_connection()
try:
with conn.cursor() as cur:
cur.execute(sql, params)
conn.commit()
finally:
conn.close()
# ======================================================
# SELECT → pandas DataFrame
# ======================================================
def fetch_df(sql: str) -> pd.DataFrame:
conn = get_connection()
try:
return pd.read_sql(sql, conn)
finally:
conn.close()