pandas连接mysql数据库

安装

pip install sqlalchemy
pip install pymysql
pip install pandas

导入包

import pandas as pd
from sqlalchemy import create_engine

连接数据库

engine = create_engine('mysql+pymysql://用户名(一般为root):密码@localhost/数据库名')

直接读取数据

data= pd.read_sql_table('表名',engine)

使用with,我们需要try,except,finally,做异常判断,并且文件最终不管遇到什么情况,都要执行finally f.close()关闭文件,with方法帮我们实现了finally中f.close

​with engine.connect() as conn, conn.begin():
    data = pd.read_sql_table('表名', conn)
data

向数据库中插入数据

df = pd.read_XXX('文件路径').head(10)
df.to_sql('表名',engine,if_exists='append')

查看df信息

df.info()

导出csv数据

df.to_csv('/home/shanghaimei/Desktop/name.csv')

你可能感兴趣的:(pandas连接mysql数据库)