Inserting Data using Connector/Python

In the last lesson, we have created the database called blog along with two tables category and post. In this lesson, we will insert some rows into the tables.

Inserting a single row

How it works:

  1. In line 5, we insert a new category into the category table
  2. In line 6, we read the value of last inserted id using the lastrowid attribute of the cursor object.
  3. In line 8, we create data for the new post and in line 10, we execute the insert statement into the post table.
  4. Finally, in line 14, we are calling the commit() method to save the changes to the database. This is necessary if you don’t call the commit() method your changes will not be saved into the database.

Bulk Insert

The following listing inserts rows in bulk into the category and post table.

Leave a Comment