作者热门文章
- r - 以节省内存的方式增长 data.frame
- ruby-on-rails - ruby/ruby on rails 内存泄漏检测
- android - 无法解析导入android.support.v7.app
- UNIX 域套接字与共享内存(映射文件)
最近开始学习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/
我是一名优秀的程序员,十分优秀!