在SQLite中sqlite3.connect和关闭有多贵?

pro*_*eek 3 sqlite pysqlite

我使用connect()和cursor()来使用SQLite

self.connector = sqlite3.connect(self.dbFile)
self.cursor = self.connector.cursor()

并且close()停止使用它.

self.cursor.close()

它们的价格(处理时间)有多贵?它是如此昂贵,只有绝对必要的使用它是必要的吗?或者,在功能中多次使用它是否可以?

添加

我使用以下简单代码进行了测试.proc1()使用在运行查询时始终打开和关闭的代码,proc2()只运行一次.

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
Run Code Online (Sandbox Code Playgroud)

结果如下.

0.00157478599548
0.000539195966721
Run Code Online (Sandbox Code Playgroud)

Don*_*ows 5

连接相当昂贵 - 它们对应于打开文件 - 但游标并不是那么多,因为你需要[1].什么做的成本是交易开始,当有一个插入或更新特别承诺(或者,如果你创建课程表或索引)即使你是自动提交模式.这是因为数据库引擎必须在完成提交之前将数据同步到磁盘(持久性保证所需),而这在现代硬件上只是非常昂贵.(事务开始成本是因为它们需要对DB文件进行一些锁定,这可能会产生影响.)

报表汇编也可能花费一些; 尽可能重用编译语句.当然,无论如何你应该这样做.为什么?这是因为你永远不应该将用户数据放在生成的SQL中; 这不仅会导致SQL注入漏洞的问题,而且还会强制数据库引擎在每次运行时重新编译语句.编译语句既安全又可能(更快).


[1]当然,使用比你需要的更多游标是愚蠢的.这只是浪费时间和精力.