我最近开始学习 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)
我只是想知道哪个更有效并且更频繁地使用?