python - For Loop 或 executemany - Python 和 SQLite3

标签 python sql for-loop sqlite executemany

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

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

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

关于python - For Loop 或 executemany - Python 和 SQLite3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43785569/

相关文章:

java - HSQLDB 神秘异常消息 : "feature not supported"

python - 从 for 循环和列表写入 .csv 文件

php - Twig 数组到字符串的转换

使用目标 ="blank"构建 URL 的 Python 脚本

python - 如何定义 "operator()"C++ 类方法的 python pybind11 绑定(bind)?

python - 在 python 中对 csv 进行排序没有发生

Python POST 请求直到在谷歌应用引擎上等待超时时间后才发送请求

php - Web 表单中的外键

php - 为什么 mysqli 插入不起作用?

JavaFX 在 for 循环期间暂停而不使用 Thread.Sleep()