본문 바로가기
IT Information/DevOps

개인 프로젝트 리뷰 - Pandas, Pymysql

by foons 2022. 10. 30.
반응형

파일은 xlsx 형식으로 다운로드 되었고, 해당 파일에서 필요한 부분을 선택하여 Database 에 적재하는 작업이 남았습니다.

 

ford_excel_1 = glob2.glob('/data/mail/*.xlsx')

 

첫 번째로 파일을 읽습니다.

 

def insert_db():
    conn = pymysql.connect(host=db_host,user=db_user,password=db_pass,db=db_name,charset='utf8')
    cur = conn.cursor()
    sql = "insert into usage (id, date, franchisee, used) value (%s, %s, %s, %s)"
    for file in ford_excel_1:
        df = pd.read_excel(file,skiprows=[0,1,2])
        df_v1 = pd.read_excel(file,usecols = [1,2,3,4,9],skiprows=[0,1],skipfooter=2)
        list_value = []
        for index in df_v1.iterrows():
            if index[1]["가맹점"] == "서비스":
                pass
            elif str(index[1][2]) == "nan":
                pass
            elif str(index[1][2]) == "\xa0":
                pass
            elif index[1]["가맹점"] == "할인":
                pass
            elif index[1]["가맹점"] == "청구할인":
                pass
            else:
                if index[1]["이용카드"] == "000":
                    list_value.append((1, index[1][0], index[1][3], int(index[1][4].replace(',',''))))
                else:
                    list_value.append((2, index[1][0], index[1][3], int(index[1][4].replace(',',''))))
        cur.executemany(sql, list_value) ## 일괄 적재
        conn.commit()
    conn.close()

* python에서 mysql 데이터를 다루는 방식

- pymysql 모듈을 Import 합니다.

- pymysql.connect() 메소드를 사용하여 mysql 에 connection 합니다. (파라메터는 호스트명, 로그인, 암호, DB 등)

- db 접속 후 cursor 메서드를 호출하여 cursor 객체를 가져옵니다. db cursor 는 fetch 동작을 관리하는데 사용 됩니다.

- cursor 객체의 execute() 메서드를 사용하여 sql 문장을 DB에 전달합니다.

- SQL 쿼리의 경우 cursor 객체의 fetchall, fetchone, fetchmany 등의 메서드를 사용하여 데이터를 서버로 부터 가져오고, fetch 된 데이터를 사용합니다.

- (필수) connection 종료를 위해 close() 를 꼭 사용합니다.

 

 

파일을 pandas 를 통하여 읽고, excel 에서 skip 할 행을 정리하고, 실제 사용할 컬럼을 정리합니다.

 

또한, if 문 내에서는 row 를 읽어 필요없는 데이터를 분별합니다.

 

 

cursor 에 executemany 를 통하여 list 에 올라온 파일을 한번에 insert 합니다.

 

 

전체 Code 가 궁금하시다면 하단의 링크를 참고 부탁드립니다.

https://github.com/foonsoo/project/blob/master/save_money/python/logic/into_db/main.py

반응형