我最近开始学习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语句会产生大量开销,如果您一次插入一行,则会一遍又一遍地产生该开销。
executemany
只要简单易行,就应该选择批处理插入。
在某些情况下,编写一次插入 一行的算法可能要简单得多。例如,如果您一次从某处接收数据,则在获取数据 时仅插入它可能会更简单,而不是 在保存大量 数据时先建立列表并进行一次插入。在这种情况下,您需要考虑性能 和代码简单性之间的权衡。通常最好从简单的 方法开始(一次插入一行),然后仅 在发现其性能不佳时才对其他内容进行优化。