프로그래밍/DB

postgresql 테이블을 csv로 저장하기 (with pandas)

kugancity 2019. 1. 15. 21:03
반응형




postgresql 테이블을 csv로 저장하기 (with pandas)





flask에서 postgreSQL 테이블 내용을 csv로 저장하는 함수 작성을 하고 기록해둔다.

처음에는 psycopg2에서 제공하는 함수를 사용해볼까 했는데 

함수 자체의 설명도 부족하고 어차피 기계 실험해야 하면 pandas 사용해야 해서 

pandas 의 read_sql, to_csv의 함수를 사용했는데 간편하고 좋은 것 같다. 

 



import psycopg2 as pc

import pandas as pd



dataReceive = request.get_json()

df = get_data(dataReceive)


def get_data(req_data):

    try:

      conn = pc.connect("dbname=디비이름 user=계정 password=암호")

      curs = conn.cursor()

      sql = "Select {0}, date, region_cd, {1} From 테이블이름 where {2} > 0 order by date".format(req_data['name'], fieldstr, req_data['name'])

      df = pd.read_sql(sql, conn)

      df.to_csv("/experiment/result.csv", encoding='utf-8', header = True, doublequote = True, sep=',', index=False)

      print("CSV File has been created")

      conn.close()

    except Exception as error:

      logger.warn("ERROR in get_data function")

      logger.warn(error)

    return df




참조: https://www.mydatahack.com/how-to-bulk-load-data-into-postgresql-with-python/



728x90
반응형