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.
Cet exercice fait partie du cours
Introduction to Databases in Python
Instructions
- Build a list of dictionaries called
values_listwith two dictionaries. In the first dictionary setnameto'Anna',countto1,amountto1000.00, andvalidtoTrue. In the second dictionary of the list, setnameto'Taylor',countto1,amountto750.00, andvalidtoFalse. - Build an
insertstatement for thedatatable for a multiple insert, save it asstmt. - Execute
stmtwith thevalues_listviaconnectionand store theresults. Make surevalues_listis the second argument to.execute(). - Print the
rowcountof theresults.
Exercice interactif pratique
Essayez cet exercice en complétant cet exemple de 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)