Dev/Python

[Python] RDS(DB)에서 CSV 파일로 export 하기 (import pandas)

장그래 2022. 8. 30. 13:35
반응형


개요

RDS 데이터 백업을 위해 S3로 데이터를 정기적으로 이관해야 될 상황이 생겼다.
NIFI나 Airflow를 사용하면 관리가 용이하지만, 여러 JOB을 돌리지 않을 것이기 때문에 단순 Python 스크립트로 개발하고자 하였다.

코드

pandas란 라이브러리를 사용했고, 코드는 csv로 export는 하는 코드는 아래와 같다.

import pandas as pd

#원하는 쿼리를 작성
query = "select * from table" 
#DB접속 정보를 입력한다. rds는 host에 Endpoint를 적으면 된다.
conn = pymysql.connect(host='db-endpoint', user='user-name', password='passwd', db='db-name', charset='utf8', port=3310)
df = pd.read_sql_query(query, conn)

# db_to_csv csv_file_name을 원하는 csv 파일명으로 하면 된다.
df.to_csv('csv_file_name', index=False)

 

더 많은 예시와 API reference를 보고 싶다면 pandans 공식 홈페이지를 참조하자

https://pandas.pydata.org/docs/index.html

 

pandas documentation — pandas 1.4.3 documentation

The reference guide contains a detailed description of the pandas API. The reference describes how the methods work and which parameters can be used. It assumes that you have an understanding of the key concepts.

pandas.pydata.org

 

반응형