I have started to learn Python and SQL recently and have a question.
Using Python with SQLite3 I have written the following code:
# 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)
I noticed that I can do the same thing using a for loop instead of executemany like so:
# 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)
I'm just wondering which one is more efficient and used more often?