我正在使用 Sqlite3 python 库创建一个股票价格数据库。但是我的代码需要很长时间才能运行,不知道为什么它很慢。知道如何加快速度吗?我做错了什么吗?
我正在使用 Python 3.x,Anaconda
import pandas as pd
from googlefinance.client import get_price_data, get_prices_data, get_prices_time_data
import sqlite3
db = sqlite3.connect('database.db')
c = db.cursor()
param = {'q':'MMM', 'i':"86400",'x':"NYSE",'p':"25Y"}
end_of_day = pd.DataFrame(get_price_data(param))
end_of_day['Time']=end_of_day.index
count= len(end_of_day['Time'])
c.execute('CREATE TABLE IF NOT EXISTS MMM(date,open,high,low,close,volume)')
for i in range(0,count):
c.execute('INSERT INTO MMM(date,open,high,low,close,volume) VALUES(?,?,?,?,?,?)',
(str(end_of_day.iloc[i][5]),str(end_of_day.iloc[i][0]),str(end_of_day.iloc[i][1]),
str(end_of_day.iloc[i][2]),str(end_of_day.iloc[i][3]),str(end_of_day.iloc[i][4])))
db.commit()
c.close()
db.close()
最佳答案
您的代码花费时间是因为您对每个插入都使用提交并使用执行,而对于批量插入,您可以使用 executemany()。
尝试将所有数据绑定(bind)到元组中,然后附加到列表中,然后使用 executemany 进行快速批量插入:
_list=[]
for i in range(0,count):
_tuple=(str(end_of_day.iloc[i][5]),str(end_of_day.iloc[i][0]),str(end_of_day.iloc[i][1]),
str(end_of_day.iloc[i][2]),str(end_of_day.iloc[i][3]),str(end_of_day.iloc[i][4])))
_list.append(_tuple)
_tuple=()
c.executemany('INSERT INTO MMM(date,open,high,low,close,volume) VALUES(?,?,?,?,?,?)',(_list))
db.commit()
关于python - 使用 Sqlite3 的数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49981686/