簡體   English   中英

For Loop或executemany - Python和SQLite3

[英]For Loop or executemany - Python and SQLite3

我最近開始學習Python和SQL並且有一個問題。

使用Python和SQLite3我編寫了以下代碼:

# Use sqlite3 in the file
import sqlite3

# Create people.db if it doesn't exist or connect to it if it does exist
with sqlite3.connect("people.db") as connection:
    c = connection.cursor()

    # Create new table called people
    c.execute("""CREATE TABLE IF NOT EXISTS people(firstname TEXT, lastname TEXT, age INT, occupation TEXT)""")


    people_list = [
        ('Simon', 'Doe', 20, 'Python Master'),
        ('John', 'Doe', 50, 'Java Master'),
        ('Jane', 'Doe', 30, 'C++ Master'),
        ('Smelly', 'Doe', 2, 'Shower Master')
    ]

    # Insert dummy data into the table
    c.executemany("""INSERT INTO people(firstname, lastname, age, occupation) VALUES(?, ?, ?, ?)""", people_list)

我注意到我可以使用for循環而不是executemany來執行相同的操作:

# Use sqlite3 in the file
import sqlite3

# Create people.db if it doesn't exist or connect to it if it does exist
with sqlite3.connect("people.db") as connection:
    c = connection.cursor()

# Create new table called people
c.execute("""CREATE TABLE IF NOT EXISTS people(firstname TEXT, lastname TEXT, age INT, occupation TEXT)""")


people_list = [
    ('Simon', 'Doe', 20, 'Python Master'),
    ('John', 'Doe', 50, 'Java Master'),
    ('Jane', 'Doe', 30, 'C++ Master'),
    ('Smelly', 'Doe', 2, 'Shower Master')
]

# Insert dummy data into the table
for person in people_list:
    c.execute("""INSERT INTO people(firstname, lastname, age, occupation) VALUES(?, ?, ?, ?)""", person)

我只是想知道哪一個更有效率並且更頻繁地使用?

使用executemany的批量插入將更有效,並且隨着記錄數量的增加,性能差異通常會非常大。 執行insert語句會產生很大的開銷,如果一次插入一行,就會反復出現這種情況。

只要直接插入,您就應該更喜歡批量插入。

在某些情況下,編寫一次插入一行的算法可能要簡單得多。 例如,如果您一次從某個項目的某個位置接收數據,則可能更容易在您獲取數據時插入數據,而不是在保存大量數據時構建列表並執行單個插入。 在這種情況下,您需要考慮性能和代碼簡單性之間的權衡。 通常最好從簡單的方法開始(一次插入一行),然后如果發現它不具備性能,則只優化其他方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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