我使用 connect() 和 cursor() 来使用 SQLite
self.connector = sqlite3.connect(self.dbFile) self.cursor = self.connector.cursor()
And close() for stop using it.
self.cursor.close()
How expensive (in terms of processing time) are they? Is it so expensive that it's necessary to use it only absolutely necessary? Or, is it just OK to use it multiple times in a function?
ADDED
I tested with the following simple code. proc1() uses the code that opens and closes all the time when it runs the query, and proc2() runs only once.
from sqlite import *
import timeit
import math
def proc1():
db = SQLiteDB("./example.db", False)
db.getOpenRunClose("SELECT * from Benchmark")
db.getOpenRunClose("SELECT * from Benchmark")
db.getOpenRunClose("SELECT * from Benchmark")
db.getOpenRunClose("SELECT * from Benchmark")
db.getOpenRunClose("SELECT * from Benchmark")
db.getOpenRunClose("SELECT * from Benchmark")
def proc2():
db = SQLiteDB("./example.db")
res = db.runSQLToGetResult("SELECT * from Benchmark")
res = db.runSQLToGetResult("SELECT * from Benchmark")
res = db.runSQLToGetResult("SELECT * from Benchmark")
res = db.runSQLToGetResult("SELECT * from Benchmark")
res = db.runSQLToGetResult("SELECT * from Benchmark")
res = db.runSQLToGetResult("SELECT * from Benchmark")
db.close()
if __name__ == '__main__':
t = timeit.Timer(proc1)
count = 5000
print t.timeit(count) / count
t = timeit.Timer(proc2)
count = 5000
print t.timeit(count) / count
结果如下。
0.00157478599548
0.000539195966721
最佳答案
连接相当昂贵——它们对应于打开文件——但游标不是非常多,所以你需要多少就用多少[1]。 做 的成本是事务开始,尤其是在有插入或更新(当然,或者如果您创建表或索引)时提交,即使您处于自动提交模式。这是因为数据库引擎必须在完成提交之前将数据同步到磁盘(需要持久性保证),而这在现代硬件上非常昂贵。 (事务开始成本是因为它们需要对数据库文件进行一些锁定,这可能会产生影响。)
语句的编译也可能会花费一些;如果可能,重用已编译的语句。当然,无论如何你都应该这样做。为什么?这是因为您永远不应该将用户数据放入生成的 SQL 中;这不仅会导致 SQL 注入(inject)漏洞的麻烦,还会迫使数据库引擎在您每次运行时重新编译该语句。编译语句既更安全,也(可能)更快。
[1] 当然,使用超出需要的游标是很愚蠢的。这简直是在浪费时间和精力。
关于sqlite - SQLite 中的 sqlite3.connect 和 close 有多贵?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3747232/