ITPub博客

首页 > IT职业 > IT生活 > pandas连接mysql数据库

pandas连接mysql数据库

IT生活 作者:lgw 时间:2021-09-09 10:06:40 0 删除 编辑

安装

pip install sqlalchemy
pip install pymysql
pip install pandas

导入包

import pandas as pdfrom 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')



作者:_Haimei
链接:https://www.jianshu.com/p/d3b975d729b3


来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/2751/viewspace-2816564/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-04-16

  • 博文量
    94
  • 访问量
    628