MulaiMulai sekarang secara gratis

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.

Latihan ini adalah bagian dari kursus

Introduction to Databases in Python

Lihat Kursus

Petunjuk latihan

  • Build a list of dictionaries called values_list with two dictionaries. In the first dictionary set name to 'Anna', count to 1, amount to 1000.00, and valid to True. In the second dictionary of the list, set name to 'Taylor', count to 1, amount to 750.00, and valid to False.
  • Build an insert statement for the data table for a multiple insert, save it as stmt.
  • Execute stmt with the values_list via connection and store the results. Make sure values_list is the second argument to .execute().
  • Print the rowcount of the results.

Latihan interaktif praktis

Cobalah latihan ini dengan menyelesaikan kode contoh berikut.

# 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)
Edit dan Jalankan Kode