-
Python] Postgresql결과를 CSV 파일로 저장 하기Python 2018. 10. 5. 16:54728x90
Python] Postgresql결과를 CSV 파일로 저장 하기
SQL의 결과를 CSV 파일로 저장하는 간단한 프로그램이다.
제약 조건은 다음과 같다.
- 1000만건 이상의 데이터가 있으므로 페이징 처리가 되어야 한다.
- 테이블명은 년_월_일_시간 형식이다.
- 시간은 2시간씩 텀을 가지고 있다.
- 결과 파일은 테이블 명과 동일 해야 한다.
프로그램은 다음과 같다.
# -*- coding: utf-8 -* import psycopg2 import csv import time pagination_size = 100000 table_name = "wk_log_2018_08_{}.tb_log_http_2018_08_{}_{} " sql = "select host, uri, srvAdd, cliAdd, srvprt, rcvTime from " + table_name sql_cnt = "select count(*) from " + table_name limit = " offset {} limit " + str(pagination_size) def save_db_data(rows, save_file): with open(save_file + ".log", 'wb') as csv_file: csv_w = csv.writer(csv_file, delimiter="|") for row in rows: row_list = list(row) csv_w.writerow(row_list) def use_pagination(): try: with psycopg2.connect("dbname='admin' user='admin' host='localhost' password='admin'") as conn: with conn.cursor() as cur: for day in xrange(1, 19): for hour in xrange(0, 24, 2): cur.execute(sql_cnt.format("{0:02d}".format(day), "{0:02d}".format(day), "{0:02d}".format(hour))) time.sleep(1) for x in xrange(0, cur.fetchone()[0], pagination_size): cur.execute(sql.format("{0:02d}".format(day), "{0:02d}".format(day), "{0:02d}".format(hour)) + limit.format(x)) rows = cur.fetchall() if len(rows) > 0: save_db_data(rows, table_name.format("{0:02d}".format(day), "{0:02d}".format(day), "{0:02d}".format(hour)) + "_" + str(x)) else: break; except Exception as e: print("I am unable to connect to the database: " + str(e)) if __name__ == "__main__": use_pagination()
파이썬을 이용하면 참 쉽줘~
728x90'Python' 카테고리의 다른 글
암호화와 복호화를 AWS Encryption SDK를 활용하여 Node.js와 Python 언어로 구현 (0) 2024.06.24 구글 콜라보에서 제공하는 주피터 노트북 (0) 2019.02.06 Python3.7 설치와 몇가지 새로운 사실 & pip install 시 SSL 오류 처리 (0) 2018.10.05 Python]paramiko 모듈에서 su 명령어로 계정 전환 (0) 2018.05.18 Python에서 class 선언시 object를 꼭 상속 받자 (0) 2018.04.17