美文网首页
tushare连接mysql问题

tushare连接mysql问题

作者: 平凡啊菜 | 来源:发表于2016-08-20 22:35 被阅读1660次
    system:OSX 10.11.6
    python version:Python 3.5.2 :: Anaconda custom (x86_64)
    tushare version:0.5.0
    mysql version:Ver 14.14 Distrib 5.7.14, for osx10.11 (x86_64) using  EditLine wrapper
    

    tushare数据存储到mysql官方示例:

    from sqlalchemy import create_engine
    import tushare as ts
    
    df = ts.get_tick_data('600848', date='2014-12-22')
    engine = create_engine('mysql://user:passwd@127.0.0.1/db_name?charset=utf8')
    
    #存入数据库
    df.to_sql('tick_data',engine)
    #追加数据到现有表
    #df.to_sql('tick_data',engine,if_exists='append')
    

    在把数据存储到mysql中,碰到python连接mysql问题:

    ImportError: No module named 'MySQLdb'
    

    解决方案:知乎讨论
    python3.5不支持使用mysqldb ,使用pymysql或者mysql.connector替代。
    命令:

    pip install pymysql
    

    重点:由于python3不再支持python-mysql, 直接改用PyMySQL的话 ,一定要改连接字符

    mysql+pymysql://<username>:<password>@<host>/<dbname>[?<options>]
    

    修改后的代码示例:

    import tushare as ts
    import sys
    from sqlalchemy import create_engine
    
    def industrytodb():
        #获取sina行业分类信息
        industry_sina = ts.get_industry_classified("sina")
        print(industry_sina, sep=' ', end='\n', file=sys.stdout, flush=False)
        #获取申万行业分类信息
        industry_sw = ts.get_industry_classified("sw")
        print(industry_sw, sep=' ', end='\n', file=sys.stdout, flush=False)
        # engine = create_engine('mysql://root:123456@localhost/stockdb?charset=utf8') 
        print("连接数据库", sep=' ', end='\n', file=sys.stdout, flush=False)
        engine = create_engine('mysql+pymysql://root:123456@localhost/stockdb?charset=utf8')
        print(engine, sep=' ', end='\n', file=sys.stdout, flush=False)
        # industry_sina.to_sql('industry_sina_data',engine,if_exists='append')
        # industry_sw.to_sql('industry_sw_data',engine,if_exists='append')
        industry_sina.to_sql('industry_sina_data',engine)
        industry_sw.to_sql('industry_sw_data',engine)
    
    if __name__ == '__main__':
        # 获取sina和申万行业分类信息
        industrytodb()
    

    相关文档:
    MySQL — SQLAlchemy 1.0 Documentation
    PyMySQL/PyMySQL · GitHub

    赞赏是最真诚的认可

    相关文章

      网友评论

          本文标题:tushare连接mysql问题

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