Programming/Python
[Python, MySQL] Python에서 DB 접속해 Data 다운받기 1
_Sun_
2023. 1. 27. 16:33
DB에 있는 데이터를 python으로 불러와서 바로 작업(ML,DL 등등)하고 싶을 때 할 수 있는 방법.
해당 작업은 Vscode의 주피터 파일을 열어 진행하였다.
pymysql 라이브러리 설치
!pip install pymysql
필요한 라이브러리 임포트
import pymysql.cursors
import pandas as pd
DB 접속
# DB 접속
connection = pymysql.connect(host='호스트명',
port=포트번호 ,
db='db명',
user='user명',
password='pw입력',
charset='utf8',
cursorclass= pymysql.cursors.DictCursor)
참고로 포트번호는 int 타입으로 넣어야 한다.
데이터 Dataframe 형식으로 다운로드
cursor = connection.cursor()
# 데이터를 불러오기 위한 SQL문
sql ="select * from 스키마명.테이블명"
# 데이터 읽는 과정
cursor.execute(sql)
result = cursor.fetchall()
# DataFrame으로 변환
df = pd.DataFrame(result)
df.head()
sql에서 쿼리문을 작성하면 쿼리문 형식에 맞는 데이터를 불러올 수 있다.