Inserting multiple records at once
It's time to practice inserting multiple records at once!
As Jason showed you in the video, when inserting multiple records at once, you do not use the .values()
method. Instead, you'll want to first build a list of dictionaries that represents the data you want to insert, with keys being the names of the columns.
in the .execute()
method, you can pair this list of dictionaries with an insert
statement, which will insert all the records
in your list of dictionaries.
This exercise is part of the course
Introduction to Databases in Python
Exercise instructions
- Build a list of dictionaries called
values_list
with two dictionaries. In the first dictionary setname
to'Anna'
,count
to1
,amount
to1000.00
, andvalid
toTrue
. In the second dictionary of the list, setname
to'Taylor'
,count
to1
,amount
to750.00
, andvalid
toFalse
. - Build an
insert
statement for thedata
table for a multiple insert, save it asstmt
. - Execute
stmt
with thevalues_list
viaconnection
and store theresults
. Make surevalues_list
is the second argument to.execute()
. - Print the
rowcount
of theresults
.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Build a list of dictionaries: values_list
values_list = [
{'name': ____, 'count': ____, 'amount': ____, 'valid': ____},
____
]
# Build an insert statement for the data table: stmt
stmt = ____
# Execute stmt with the values_list: results
results = connection.execute(____, ____)
# Print rowcount
print(results.rowcount)