Insert DataFrame to MySQL

choify·2022년 7월 19일

index

  • 라이브러리 설치
  • MySQL 연결하기
  • DataBase에 DataFrame 넣기
  • DataBase에 있는 Table 삭제하기

라이브러리 설치

!pip install pymysql
!pip install sqlalchemy

mysql 연결

import pymysql
from sqlalchemy import create_engine

MYSQL_HOSTNAME = 'localhost' # you probably don't need to change this
MYSQL_USER = 'root'
MYSQL_PASSWORD = 'PASSWORD'
MYSQL_DATABASE = 'DB_NAME'

connection_string = f'mysql+pymysql://{MYSQL_USER}:{MYSQL_PASSWORD}@{MYSQL_HOSTNAME}/{MYSQL_DATABASE}'
# connect_args = {'ssl': {'ca': '/content/rds-ca-2015-root.pem'}}

db = create_engine(connection_string)

DataBase에 DataFrame 넣기

df.to_sql(con=db, name='SEOUL_TB', if_exists='append', index=False)
  • if_exists : Table이 존재하는 경우에 대한 옵션 - append, fail, replace

  • append : 존재하는 테이블에 값 저장(데이터프레임의 길이나 타입이 일치하지 않으면 오류), 테이블 존재하지 않을 경우 테이블 생성 후 값 저장

  • fail : ValueError 발생

  • replace : Table Drop 후 새로 생성하고 값 저장

DataType 설정하기

import sqlalchemy

datatypes = {"EmployeeNumber": "sqlalchemy.INT", "EmployeeName": "sqlalchemy.String(50)"}

df.to_sql(name='building', con=db_connection, if_exists='append', index=False, dtype=datatypes)

DataBase에 있는 데이터 출력하기

query = """
SELECT * FROM SEOUL_TB
""".format(MYSQL_DATABASE)

events_df = pd.read_sql(query, db)

print(events_df)

DataBase에 있는 Table 삭제하기

conn = pymysql.connect(host=MYSQL_HOSTNAME, user=MYSQL_USER, passwd=MYSQL_PASSWORD, database=MYSQL_DATABASE)

cur = conn.cursor()

query = """
DROP TABLE SEOUL_TB
""".format(MYSQL_DATABASE)
cur.execute(query)

conn.close()
profile
Hello =)

0개의 댓글