利用Pandas读MySQL数据
# 导入相关库
import pandas as pd
from sqlalchemy import create_engine
# 初始化数据库连接,使用pymysql模块
# MySQL的用户:root, 密码:123456, 端口:3306,数据库:test
engine = create_engine('mysql+pymysql://root:123456@localhost:3306/test')
# 查询语句,选出employee表中的所有数据
sql = '''
SELECT * FROM test;
'''
# read_sql_query的两个参数: sql语句, 数据库连接
df = pd.read_sql_query(sql, engine)
# 输出test表的查询结果
print(df)
结果如图:
利用Pandas写入MySQL
# 新建pandas中的DataFrame
df = pd.DataFrame(字典数据)
# 将新建的DataFrame储存为MySQL中的数据表,不储存index列
df.to_sql('test', engine, index= False)