99번째 줄: |
99번째 줄: |
| | | | | |
| |객체=커서객체.fetchone() | | |객체=커서객체.fetchone() |
| + | |} |
| + | |
| + | = 다양한 사용법 = |
| + | |
| + | == 백업 == |
| + | sql 자체에 백업기능이 있지만, 어째서인지, 행의 갯수도 달라지고, 용량도 달라진다. 반면 dataframe의 데이터를 직접 박아넣는 것은 행의 갯수도 크게 달라지지 않고(1,2개는 달라지는데, 이유를 모르겠다;), 용량도 오히려 많이 줄어든다.(아마 로그는 옮겨지지 않기 때문일듯..) |
| + | {| class="wikitable" |
| + | !과정 |
| + | !설명 |
| + | |- |
| + | |백업할 DB 연결 |
| + | |<syntaxhighlight lang="python"> |
| + | ##### 백업할 DB 연결 및 테이블리스트 얻기. |
| + | import pymysql |
| + | from_db = pymysql.connect(host='연결할호스트', port=3306, db='coin_minute_info', user="유저", passwd='비밀번호', charset='utf8') |
| + | from_cur = from_db.cursor() |
| + | |
| + | from_cur.execute('SHOW TABLES') |
| + | tables = from_cur.fetchall() |
| + | table_list = [] |
| + | for i in tables: |
| + | table_list.append(i[0]) |
| + | print('테이블리스트 생성 완료.') |
| + | </syntaxhighlight> |
| + | |- |
| + | |복원할 DB 연결 및 테이블 생성 |
| + | |<syntaxhighlight lang="python"> |
| + | to_db = from_db = pymysql.connect(host='localhost', port=3306, db='coin_minute_info', user="root", passwd='비밀번호', charset='utf8') |
| + | to_cur = to_db.cursor() |
| + | for i in table_list: |
| + | sql='CREATE TABLE IF NOT EXISTS {} (time DATETIME, start FLOAT, close FLOAT, \ |
| + | high FLOAT, low FLOAT, volume FLOAT)'.format(i) |
| + | to_cur.execute(sql) # 테이블 따라서 생성. |
| + | to_db.commit() # 반영. |
| + | print('테이블 복사 완료') |
| + | </syntaxhighlight> |
| + | |- |
| + | |dataframe을 sql로 넣어주는 모듈 준비 |
| + | |<syntaxhighlight lang="python"> |
| + | from sqlalchemy import create_engine |
| + | engine = create_engine("mysql+pymysql://{user}:{pw}@{domain}/{db}" |
| + | .format(user="root", # sql 계정 입력. |
| + | domain='localhost', # 도메인 주소 |
| + | pw="vudghk99", # sql 비밀번호 입력. |
| + | db="coin_minute_info")) # 연결할 db이름 입력. |
| + | </syntaxhighlight> |
| + | |- |
| + | |옮기기 실행 |
| + | |<syntaxhighlight lang="python"> |
| + | import pandas as pd |
| + | |
| + | for i in table_list: |
| + | from_cur.execute('select * from {}'.format(i)) |
| + | data = from_cur.fetchall() |
| + | data = pd.DataFrame(data) |
| + | data.rename(columns={0:'time', 1:'start', 2:'close', 3:'high', 4:'low', 5:'volume'}, inplace=True) |
| + | data.set_index('time', inplace=True) |
| + | print(data) |
| + | table_name = i |
| + | data.to_sql(table_name, con = engine, if_exists = 'append', chunksize = 1000) |
| + | </syntaxhighlight> |
| |} | | |} |
| | | |