Data/Python
[Python] psycopg2 라이브러리를 활용하여 table column얻기
재융
2022. 3. 22. 00:56
반응형
airflow쪽에 dag정보를 얻어오기위해 postgre db를 연결하는 코드를 만든이후에 column에 대한 정보값을 얻으려면 아래와같이 작업해주면된다.
- column정보값을 얻는 코드는 sql 쿼리를 실행한 이후에 cur.description 을 실행해주면된다
import psycopg2
try:
# db connect
conn = psycopg2.connect(
host = "",
dbname = "",
user = "",
password = ""
)
cur = conn.cursor()
# run sql code
cur.execute("""
select *
from (
select dag_id, count(distinct id) as CountId
from dag_run
group by 1) A
where CountId = 2
limit 10
""")
# get column name
print(cur.description)
rows = cur.fetchall()
for i in rows:
print(i)
except Exception as e:
print(e)
반응형