1. PyMySQL 패키지 설치
> pip install PyMySQL
ref) https://pypi.org/project/PyMySQL/
> pip install pandas
** pandas lib : DataFrame 라이브러리
ref) https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html
2. Source
import pymysql
import pandas as pd
# db 정보 설정
test_db = pymysql.connect(
user='root',
passwd='********',
host='localhost',
port=3306,
db='hybris',
charset='utf8'
)
try:
# 커서 설정
cursor = test_db.cursor(pymysql.cursors.DictCursor)
sql = "SELECT * FROM bankaccount"
cursor.execute(sql)
# fetchall() 모든 데이터를 한 번에 가져올 때 사용
# fetchone() 한 번 호출에 하나의 행만 가져올 때 사용
# fetchmany(n) n개만큼의 데이터를 가져올 때 사용
result = cursor.fetchall()
result = pd.DataFrame(result)
print(result)
finally:
cursor.close()
test_db.close()
'Python > DB' 카테고리의 다른 글
Python procedure 호출 (mysql) (1) | 2021.05.27 |
---|