簡體   English   中英

當涉及到以注釋開頭的 SQL 查詢時,Python sqlite3 模塊是否存在錯誤和緩慢?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM