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數(shù)據(jù)存儲到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')
#存入數(shù)據(jù)庫
df.to_sql('tick_data',engine)
#追加數(shù)據(jù)到現(xiàn)有表
#df.to_sql('tick_data',engine,if_exists='append')
在把數(shù)據(jù)存儲到mysql中,碰到python連接mysql問題:
ImportError: No module named 'MySQLdb'
解決方案:知乎討論
python3.5不支持使用mysqldb ,使用pymysql或者mysql.connector替代。
命令:
pip install pymysql
重點(diǎn):由于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行業(yè)分類信息
industry_sina = ts.get_industry_classified("sina")
print(industry_sina, sep=' ', end='\n', file=sys.stdout, flush=False)
#獲取申萬行業(yè)分類信息
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("連接數(shù)據(jù)庫", 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和申萬行業(yè)分類信息
industrytodb()
相關(guān)文檔:
MySQL — SQLAlchemy 1.0 Documentation
PyMySQL/PyMySQL · GitHub
非常好的模式,讓我今年收益翻倍的文章,強(qiáng)烈推薦分享下:
2020年4月至6月凈利潤斷層實(shí)戰(zhàn)小結(jié)-真香~