python - 獲取到的數(shù)據(jù)生成新的mysql表
問題描述
# -*- conding:utf8 -*-import tushare as tsimport pymysqlconn = pymysql.connect(host=’127.0.0.1’, port=3306, user=’root’, passwd=’root’, db=’test’)cursor = conn.cursor() #創(chuàng)建游標(biāo)today_data = ts.get_today_all() #把獲取到的數(shù)據(jù)給today_data
代碼如上,可以成功連接數(shù)據(jù)庫,創(chuàng)建游標(biāo),獲取到數(shù)據(jù)。問題是:today_data獲取到的數(shù)據(jù)有多個字段(code、name、changepercent、trade、open high、low、settlement),那如何在獲取到數(shù)據(jù)的時候,生成一張新表?新表的字段和獲取到的字段一致。
可能我描述的不夠清楚,我是想把變量today_data里的數(shù)據(jù)插入到mysql的表中。把變量里的多個字段多條記錄插入表里,或者直接新建一個表。
問題解答
回答1:字段都知道,就直接用SQL創(chuàng)建表,表名你也是知道的,然后insert數(shù)據(jù)
回答2:更簡單是用pandas的to_sql命令,可以直接整體寫入sql的一張表。
這條命令有一個參數(shù)if_exists,如果設(shè)置為append,在沒有表的前提下,就會自建。
對于你用tushare獲得的本來就是pandas格式的數(shù)據(jù),這是最簡單最直接的法子。
回答3:最簡單的莫過于在處理數(shù)據(jù)之后,使用 INSERT INTO …… VALUES vars ……
cursor.execute('INSERT INTO today_data (code、name、changepercent、trade、open high、low、settlement) VALUES (’{}’,’{}’,’{}’,’{}’,’{}’,’{}’,’{}’)'.format(code、name、changepercent、trade、open high、low、settlement))
相關(guān)文章:
1. mac連接阿里云docker集群,已經(jīng)卡了2天了,求問?2. docker網(wǎng)絡(luò)端口映射,沒有方便點(diǎn)的操作方法么?3. vim - docker中新的ubuntu12.04鏡像,運(yùn)行vi提示,找不到命名.4. angular.js - angular內(nèi)容過長展開收起效果5. 為什么我ping不通我的docker容器呢???6. html5和Flash對抗是什么情況?7. golang - 用IDE看docker源碼時的小問題8. 前端 - @media query 使用出現(xiàn)的問題?9. 我何時應(yīng)該在Java中使用JFrame.add(component)和JFrame.getContentPane()。add(component)10. spring-mvc - spring-session-redis HttpSessionListener失效

網(wǎng)公網(wǎng)安備