ComputerLanguage_Program/PYTHON
[Python] 쿼리가 기록된 txt 파일을 이용한 쿼리 실행(pymysql)
pbj0812
2021. 3. 2. 00:31
0. 플로우 차트
- 쿼리가 작성된 txt 를 읽어 해당 쿼리를 이용해 MySQL 에서 데이터를 가져온 뒤 pandas 의 DataFrame 형태로 출력
1. 텍스트 파일 내용
SELECT
*
FROM pbj_db.rownum_test;
2. 실습
1) library 호출
import pymysql
import pandas as pd
2) db 연결
db = pymysql.connect(host='127.0.0.1', port=3306, user='root', db='pbj_db', charset='utf8', cursorclass=pymysql.cursors.DictCursor)
cursor = db.cursor()
3) 파일 읽기
f = open("./sql.txt", 'r')
sql = ''
while True:
line = f.readline()
if not line: break
a = str(line)
sql = sql + a
f.close()
4) 쿼리 실행
cursor.execute(sql)
result = cursor.fetchall()
db.close()
5) 데이터프레임화
df = pd.DataFrame(result)
2. 결과