sqlite - SQLite 中的 sqlite3.connect 和 close 有多贵?

标签 sqlite pysqlite

我使用 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/

相关文章:

python - 如何在 pysqlite 中启用事务性 DDL?

performance - Sqlite追加数据性能线性下降,这个可以解决吗?

python - 创建 Django 应用程序时如何解决 No module named _sqlite3?

python - 使用可变数量的 WHERE 子句来匹配任意数量的关键字 pysqlite

visual-studio-2010 - Visual Studio 2010 中的 SQLite DateTime <无法读取数据>

python - '从 sqlite3 导入 dbapi2 作为 sqlite 3' vs ' 导入 sqlite3'?

CentOS 上的 Django

sqlite - 使用 2 列在 sqlite 中选择 2 个日期

android - 在查询中将长转换为日期

android - 寻找 BackupAgent(用于 sqlite 数据库)示例