mysql把游标数据存入表中_利用Python爬股票数据并存入数据库Mysql
生活随笔
收集整理的這篇文章主要介紹了
mysql把游标数据存入表中_利用Python爬股票数据并存入数据库Mysql
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
直接上代碼,小白也能爬股票.........
import tushare as ts import mysql.connector import re,time #創(chuàng)建所有股票的表格以及插入每支股票的近段時間的行情,這個文件只需要執(zhí)行一次!!! #想要寫入哪一段時間的數(shù)據(jù)只需要修改starttime,endtime的時間就可以了 def everdate(starttime,endtime): #獲取所有有股票 stock_info = ts.get_stock_basics() #連接數(shù)據(jù)庫 conn = mysql.connector.connect(host="localhost",user="root",password="1234",db="jie",port=3306,auth_plugin='mysql_native_password') cursor = conn.cursor() codes = stock_info.index a = 0 #通過for循環(huán)以及獲取A股只數(shù)來遍歷每一只股票 for x in range(0,len(stock_info)): if re.match('000',codes[x]) or re.match('001',codes[x]) or re.match('002',codes[x]) or re.match('6',codes[x]) or re.match('3',codes[x]): #以stock_加股票代碼為表名稱創(chuàng)建表格 cursor.execute('create table stock_' + codes[x] + ' (code varchar(6),date varchar(32),open varchar(32),close varchar(32),high varchar(32),low varchar(32),volume varchar(32),p_change varchar(32),ma5 varchar(32),ma10 varchar(32),ma20 varchar(32),v_ma5 varchar(32),v_ma10 varchar(32),v_ma20 varchar(32))') #利用tushare包獲取單只股票的階段性行情 df = ts.get_hist_data(codes[x],starttime,endtime) print('%s的表格創(chuàng)建完成'%codes[x]) a += 1 #這里使用try,except的目的是為了防止一些停牌的股票,獲取數(shù)據(jù)為空,插入數(shù)據(jù)庫的時候失敗而報錯 #再使用for循環(huán)遍歷單只股票每一天的行情 try: for i in range(0,len(df)): #獲取股票日期,并轉(zhuǎn)格式 times = time.strptime(df.index[i],'%Y-%m-%d') time_new = time.strftime('%Y%m%d',times) #插入每一天的行情 cursor.execute('insert into stock_'+codes[x]+ ' (code,date,open,close,high,low,volume,p_change,ma5,ma10,ma20,v_ma5,v_ma10,v_ma20) values (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)' % (codes[x],time_new,df.open[i],df.close[i],df.high[i],df.low[i],df.volume[i],df.p_change[i],df.ma5[i],df.ma10[i],df.ma20[i],df.v_ma5[i],df.v_ma10[i],df.v_ma20[i])) except: print('%s這股票目前停牌'%codes[x]) try: cursor.execute('insert into allstock_k_01_02 select * from stock_'+codes[x])cursor.execute('DROP TABLE stock_'+codes[x]) except:continue conn.close() cursor.close() #統(tǒng)計總共插入了多少張表的數(shù)據(jù) print('所有股票總共插入數(shù)據(jù)庫%d張表格'%a) everdate('2020-02-05','2020-02-06')
講解一下,運行腳本前要先創(chuàng)建一個叫allstock_k_01_02 的空表是總表,帶上code到V_ma20這些字段。
安裝好其他包,再改一下以下數(shù)據(jù)庫連接參數(shù)就可以運行了。
(host="localhost",user="root",password="1234",db="jie",port=3306,auth_plugin='mysql_native_password')
以及:
cursor.execute('DROP TABLE stock_'+codes[x]) #這一句刪掉就會生成3700個股表
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎勵來咯,堅持創(chuàng)作打卡瓜分現(xiàn)金大獎總結(jié)
以上是生活随笔為你收集整理的mysql把游标数据存入表中_利用Python爬股票数据并存入数据库Mysql的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: go读取excel_Golang操作Ex
- 下一篇: ajax从mysql提取数据在html中