파이썬으로 연동한 MYSQL - 날짜 입력에 따른 sql문 동작, 결과값 엑셀 파일로 저장

테리·2022년 5월 26일
0
post-thumbnail
  • 파이썬으로 MYSQL에 연동 후 원하는 날짜를 입력해 그에 맞는 데이터만 추출하기 위해 날짜를 입력받는 함수식을 추가했다
  • 이후 지표를 더 편하게 정리하기 sql 테이블 데이터를 python pandas 데이터프레임에 삽입 후 엑셀 파일로 추출하는 함수를 넣어 간단하게 복사+붙여넣기만 할 수 있도록 만들었다.
import pandas as pd
import xlsxwriter
import pymysql
from sshtunnel import SSHTunnelForwarder
import datetime


def sqlindi():
    day1 = input('시작 날짜를 입력해 주세요 (yyyy.mm.dd): ')
    day2 = input('종료 날짜를 입력해 주세요 (yyyy.mm.dd): ')
    yyyy1, mm1, dd1 = day1.strip().split('.')
    yyyy2, mm2, dd2 = day2.strip().split('.')
    sd = datetime.date(int(yyyy1),int(mm1),int(dd1)) - datetime.timedelta(days=1)
    ed = datetime.date(int(yyyy2),int(mm2),int(dd2))
    #print(sd,ed)
    def dayday(sd,ed):
        with SSHTunnelForwarder(('ssh터널 host 주소', ssh터널 IP),
                            ssh_username='ssh_username',
                            ssh_pkey='ssh_private_key',
                            remote_bind_address=('mysql_server_host', 3306(mysql_port)),
                           ) as tunnel:
            with pymysql.connect(
            host='127.0.0.1', #(local_host)
            user='db_username',
            passwd='db_password',
            db='db',
            charset='utf8',
            port=tunnel.local_bind_port,
            cursorclass=pymysql.cursors.DictCursor) as conn:  
            #DB를 조회한 결과를 Column명이 Key인 Dictionary로 저장
                
            print('날짜별 가입자 수')
            with conn.cursor() as cur:
                sql = "sql문 작성"
                cur.execute(sql)
                print(sql)
                results = cur.fetchall()
                df1 = pd.DataFrame(results)
                print(df1)
                #for result in results:
                #    print(result)
                #주석처리한 for문은 sql에서 불러온걸 한줄로 이어 붙이는게 아니라 여러 열로 붙일 때 필요. but 데이터프레임 함수를 써서 필요 없음.
                    
                    ㆍ
                    ㆍ
                    ㆍ

            print()
            print('날짜별 매출')
            with conn.cursor() as cur:
                sql10 = "sql문 작성"
                cur10.execute(sql10)
                results10 = cur10.fetchall()
                df10 = pd.DataFrame(results10)
                print(df10)
                #for result10 in results10:
                #print(result10)
                
                with pd.ExcelWriter('지표데이터.xlsx', engine='xlsxwriter') as writer:
                    df1.to_excel(writer, sheet_name='날짜별 가입자 수', index=False)
                    
                    ㆍ
                    ㆍ
                    ㆍ
                    
                    df10.to_excel(writer, sheet_name='날짜별 매출', index=False)

    print() #이건 그냥 빈칸
    print('시작일:',day1,' 종료일:',day2)
    print()
    dayday(sd,ed) #실제 결과값

참고)
pyautogui를 사용하면 입력창을 띄어 입력창을 통해 날짜를 받을 수 있다.

pip install pyautogui

이후에

import pyautogui
day1 = input('') -> day1 = pyautogui.prompt('')

이 형식으로 변경하면 된다.

profile
영화 좋아합니다

0개의 댓글