PostgreSQL(AWS RDS) to csv file 가능한 python code 예시

2020-09-03

.

import sys
import requests
import base64
import json
import logging
import psycopg2
from psycopg2.extras import RealDictCursor
import io
sys.stdout = io.TextIOWrapper(sys.stdout.detach(), encoding = 'utf-8')
sys.stderr = io.TextIOWrapper(sys.stderr.detach(), encoding = 'utf-8')


connection = psycopg2.connect(user="xxxxxxxxxxxxxxxxxxxxxxx",\
                              password="xxxxxxxxxxxxxxxxxxxxx",\
                              host="xxxxxxxxxxxxxxxxxxxxxxxxx.ap-northeast-2.rds.amazonaws.com",\
                              port="6001",\
                              database="xxxxxxxxxxxxxxxxx")
cursor = connection.cursor()

s = "SELECT * FROM test1"

# Use the COPY function on the SQL we created above.
SQL_for_file_output = "COPY ({0}) TO STDOUT WITH CSV HEADER".format(s)

# Set up a variable to store our file path and name.
t_path_n_file = "test1.csv"
with open("test1.csv", "w") as f_output:
    cursor.copy_expert(SQL_for_file_output, f_output)