美文网首页我爱编程
pandas连接mysql数据库

pandas连接mysql数据库

作者: _Haimei | 来源:发表于2018-08-08 11:11 被阅读33次

    安装

    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数据库

        本文链接:https://www.haomeiwen.com/subject/fpptbftx.html