参考:https://blog.csdn.net/zhaohansk/article/details/51935041
https://www.cnblogs.com/cymwill/p/8289367.html
pandas的数据结构dataframe和数据库中的数据结构基本相同,因此pandas提供了从数据库读取dataframe以及将dataframe写入数据库的便捷操作。
在新版的pandas中,主要是以sqlalchemy方式与数据库建立链接支持Mysql、postgresql、Oracle、MS SQLServer、SQLite等主流数据库。本例以MySql为代表,展示将从tushare中获取到的股票数据存入数据库的方法,其他类型数据库请参考sqlalchemy官方文档的create_engine部分。
一:创建链接数据库引擎
db_info = {'user': 'crawl', 'password': 'crawl', 'host': '10.2.9.12', 'database': 'ashares_trading_info' } self.engine = create_engine('mysql://%(user)s:%(password)s@%(host)s/%(database)s?charset=utf8' % db_info, encoding='utf-8')
'数据库类型+数据库驱动名称://用户名:口令@机器地址:端口号/数据库名'
engine = create_engine('mysql://scott:tiger@localhost/foo')
其中如果数据库驱动是python,请参考:
https://www.liaoxuefeng.com/wiki/001374738125095c955c1e6d8bb493182103fac9270762a000/0014021031294178f993c85204e4d1b81ab032070641ce5000
二:从数据库中读取DataFrame
sql = "SELECT * FROM {3} where shares_code = '{0}' and date >= '{1}' and date <='{2}'" \ "ORDER BY date desc;".format(code, start_date, end_date, self.tabel_name) d_trading_info = pd.read_sql(sql, con=self.engine)
三:将DataFrame写入数据库
d_shares_info.to_sql(self.tabel_name, con=self.engine, if_exists='append', index=False)#if the tabel don't exist, create it