!pip install pymysql
!pip install sqlalchemy
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)
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 후 새로 생성하고 값 저장
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)
query = """
SELECT * FROM SEOUL_TB
""".format(MYSQL_DATABASE)
events_df = pd.read_sql(query, db)
print(events_df)
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()