2017-10-27 7 views
0

Python을 사용하여 AWS의 Postgres RDS 데이터베이스에 큰 csv 파일을로드하는 가장 쉬운 방법은 무엇입니까? 로컬 포스트 그레스 인스턴스로 데이터를 전송하려면Python을 사용하여 AWS의 Postgres RDS로 큰 csv 파일 업로드

, 나는 이전에 같은 SQL 문을 실행하는 데 psycopg2 연결을 사용하고 있습니다 : 원격 AWS RDS 데이터베이스에 대해이 작업을 수행 할 때 그러나

COPY my_table FROM 'my_10gb_file.csv' DELIMITER ',' CSV HEADER; 

을,이 오류 때문에 발생 .csv 파일은 데이터베이스 서버가 아닌 내 로컬 컴퓨터에이 작동하지 않는 이유

ERROR: must be superuser to COPY to or from a file 
SQL state: 42501 
Hint: Anyone can COPY to stdout or from stdin. psql's \copy command also works for anyone. 

This answer는 설명한다.

이제 psql을 사용하여 이것을 자동화하는 파이썬 구문을 찾고 있습니다. 많은 수의 .csv 파일을 업로드해야하므로 스크립트를 자동화해야합니다.

+1

'psql의 -c "\ MY_TABLE COPY

그런 다음이 같은 psql 문을 실행해야 FROM 'my_10gb_file.csv'DELIMITER ','CSV HEADER; "가 작동합니다 ... –

답변

0

먼저 CREATE TABLE SQL 문을 사용하여 RDS Postgres에 테이블 정의를 만들어야합니다.

psql -p 5432 --host YOUR_HOST --username YOUR_USERNAME --dbname YOUR_DBNAME --command "\copy my_table FROM 'my_10gb_file.csv' DELIMITER ',' CSV HEADER" 

파이썬에서, 우리는이를 설정하고 다음과 같이 실행할 수 있습니다 :

host = "YOUR_HOST" 
username = "YOUR_USERNAME" 
dbname = "YOUR_DBNAME" 

table_name = "my_table" 
file_name = "my_10gb_file.csv" 
command = "\copy {} FROM '{}' DELIMITER ',' CSV HEADER".format(table_name, file_name) 

psql_template = 'psql -p 5432 --host {} --username {} --dbname {} --command "{}"' 

bash_command = psql_template.format(host, username, dbname, command.strip()) 

process = subprocess.Popen(bash_command, stdout=subprocess.PIPE, shell=True) 

output, error = process.communicate()