[英]Is the Python sqlite3 module bugged and slow when it comes to SQL queries that start with comments?
我注意到如果 SQL 查询以使用 --comment 格式的注释开头,我的 sqlite3 查询将花费 375 倍的时间。 这是正常行为吗? 它是内置 sqlite3 模块中的错误吗?
import pathlib
import sqlite3
import timeit
def test_do(sql):
db_path = pathlib.Path("./test.sqlite3")
con = sqlite3.connect(db_path)
cursor = con.cursor()
table_sql: str = f"""
CREATE TABLE IF NOT EXISTS test (
id INTEGER PRIMARY KEY)"""
cursor.execute(table_sql)
for i in range(1, 43000):
cursor.execute(sql, [i])
con.commit()
db_path.unlink()
sqlslow = f"""
--comment
INSERT INTO "test" ("id") VALUES (?)
"""
sqlfast = f"""
INSERT INTO "test" ("id") VALUES (?)
"""
starttimeslow = timeit.default_timer()
test_do(sqlslow)
print(f"sqlslow: {timeit.default_timer() - starttimeslow}")
starttimefast = timeit.default_timer()
test_do(sqlfast)
print(f"sqlfast: {timeit.default_timer() - starttimefast}")
结果:
sqlslow: 21.521265994
sqlfast: 0.05736106100000171
编辑:我发现 /* */ 样式注释的行为相同。
从表面上看,性能似乎与评论有关,我在 sqlite3 上看到了类似的结果(20 秒和 0.05 秒)。 但我认为它不止于此。
我用具有不同事务处理的apsw包替换了代码中的 sqlite3,使用它时,我看到两个测试都用了 20 秒。 请注意,apsw 不会像 sqlite3 那样自动为您开始事务。
然后我明确地在 43k 插入周围包含了一个事务开始/提交,两次都花费了 0.05 秒。 这是有道理的,因为这段代码应该在事务中运行得更快。
这一切都表明 sqlite3 在一种情况下使用事务(单行 INSERT),而不是在另一种情况下使用事务(带有注释和 INSERT 的多行语句)。 另外,sqlite3 的事务处理,虽然旨在让用户的事情变得更简单,但似乎有点奇怪。
而且,确实,如果我显式插入以下开始事务,那么 sqlite3 结果都很快(0.05 秒):
cursor.execute(table_sql)
cursor.execute("begin") # add this
for i in range(1, 43000):
cursor.execute(sql, [i])
con.commit()
sqlite3 测试的输出现在是:
sqlslow: 0.051317919000000004
sqlfast: 0.05007833699999999
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.