Python内置数据结构操作VS sqlite3操作

1.摘要

在同一数据库中查询某值,内置数据结构的查询速度快还是数据库sqlite3的查询速度快?针对这一问题,通过构建一个包含2500个随机数的列表,并将其插入sqlite3数据库中,利用timeit模块,分别对内置数据结构list和sqlite3查询某一值在不在数据组中进行对比。

2.代码

>>> import numpy as np
>>> import sqlite3
>>> test=np.random.randn(2500)
>>> test=test.tolist()  #数据转换
>>> a=test[100]  #待查询数据
>>> conn=sqlite3.Connection('testit.db')
>>> c=conn.cursor()
>>> c.execute('create table test(ID integer primary key autoincrement,value real)')
>>> for i in range(len(test)):
	    c.execute('insert into test values (?,?)',(i,test[i]))  #需要注意的是,与占位符?对应的应该是元组,如果是只有一个?,则对应的元组也应该是(x,),其中x是需要插入的数据。
>>> timeit.timeit('a in test',number=10000,globals=globals())  #globals=globals()保证了全局变量
0.024695289129624598
>>> timeit.timeit('c.execute("select * from test where test.value=?",(a,))',globals=globals(),number=10000)
0.1466543038781083

 3.结论

内置结构查询速度快。

##### 愿你一寸一寸地攻城略地,一点一点地焕然一新 #####
原文地址:https://www.cnblogs.com/johnyang/p/12589479.html