For循环或executemany-Python和SQLite3
我最近开始学习Python和SQL,有一个问题 使用Python和SQLite3,我编写了以下代码:For循环或executemany-Python和SQLite3,python,sql,for-loop,sqlite,executemany,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() #
# 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语句会有很大的开销,如果一次插入一行,就会一次又一次地产生这种开销
只要可以直接插入,您应该更喜欢批插入
在某些情况下,编写一个每次插入一行的算法可能要简单得多。例如,如果您一次从某个地方接收一个项目的数据,那么在获取数据时插入它可能比在保存了大量数据后建立一个列表并进行一次插入更简单。在这种情况下,需要考虑代码的性能和简单性之间的权衡。通常最好从简单的方法开始(一次插入一行),然后仅在发现性能不好时优化到其他内容。dan1111,正如我所想,感谢您的详细回复,非常感谢!