I have over ten thousand of data in python list and it take over 300 seconds to add data from list into sqlite table. I would like to know how to add multi data at the same time or the fastest method to do it.
list_example = [('ST0001', '2020-04-11', 23.0), ('ST0002', '2020-04-11', 20.0), ('ST0003', '2020-04-11', 75.0)]
First code version:
import sqlite3
def add_temp_stock_data(PART_NO, INVDATE, COST):
global conn
global c
conn = sqlite3.connect('PRODUCT_LIST.db')
c = conn.cursor()
c.execute("""CREATE TABLE IF NOT EXISTS PRODUCT_LIST (
PART_NO TEXT,
INVDATE TEXT,
COST REAL)
""",
)
with conn:
c.execute("""INSERT INTO PRODUCT_LIST (PART_NO, INVDATE, COST)
VALUES (?,?,?)""",
(PART_NO, INVDATE, COST,))
conn.commit()
for i in range(len(list_example)):
PART_NO = list_example[i][0]
INVDATE = list_example[i][1]
COST = list_example[i][2]
add_temp_stock_data(PART_NO, INVDATE, COST)
Second code version:
def add_temp_stock_data(list_example):
global conn
global c
conn = sqlite3.connect('PRODUCT_LIST.db')
c = conn.cursor()
c.execute("""CREATE TABLE IF NOT EXISTS PRODUCT_LIST (
PART_NO TEXT,
INVDATE TEXT,
COST REAL)
""",
)
for i in range(len(list_example)):
PART_NO = list_example[i][0]
print(PART_NO)
INVDATE = list_example[i][1]
print(INVDATE)
COST = list_example[i][2]
print(COST)
with conn:
c.execute("""INSERT INTO PRODUCT_LIST (PART_NO, INVDATE, COST)
VALUES (?,?,?)""",
(PART_NO, INVDATE, COST,))
print(list_example)
conn.commit()
add_temp_stock_data(list_example)
CREATE TABLEquery once, you'll need to move it out ofadd_temp_stock_data(). Don't create a new connection for each query. Just create a connection and pass it as an argument toadd_temp_stock_data(), you'll need to handle the case in which the connection closes prematurely.execute()is actually implemented asexecutemany()under the hood. You can verify this by reading the source code or you can trust this Python-specific sqlite optimization article. I'm runningexecutemany()on data like yours with 100,000 inserts in under 100ms. You may be able to shave off a little more time by usingsqlite3.Connection.executemanyinstead ofsqlite.Cursor.executemany, but there's not much more room for improvement here in the code.