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 的批量插入会更高效,并且随着记录数量的增加,性能差异通常会非常大。执行插入语句会产生很大的开销,如果您一次插入一行,就会一遍又一遍地产生这种开销。

只要简单易行,您应该更喜欢批量插入。

在某些情况下,编写一次插入一行的算法可能要简单得多。例如,如果您一次从某处接收一个项目的数据,那么在您获得它时插入它可能会更简单,而不是建立一个列表并在您保存了大量数据时进行一次插入。在这种情况下,您需要考虑性能和代码简单性之间的权衡。通常最好从简单的方法开始(一次插入一行),然后仅在您发现其他方法性能不佳时才对其进行优化。