## Module 3: Using Prepared Statements and Batch Inserts

Now, you can use Python code to read and write data to TiDB Cloud Starter cluster. But if you want to improve the performance of your application, you can use prepared statements (for precompiled and repeated execution) and efficient batch inserts (for inserting multiple rows of data into a table in a single SQL statement).

### Step 1. Using prepared statements

+ On the left **EXPLORER** of the VS Code, under folder `mysql_connector_python_demo`, click `prepared_statement.py` file, go through the sample code note line `connection.cursor(prepared=True)` and `print("Generated PK is", cursor.lastrowid)`. If you create cursor with parameter `prepared=False`, you are using the client side prepared statement only. The `cursor.lastrowid` to get the auto random ID of the recently inserted row.

+ Run `prepared_statement.py`.

  ```bash
  poetry run python mysql_connector_python_demo/prepared_statement.py
  ```

  ```output
  The generated PK is 4035225266123964417
  ```

![90%](https://public-pingcap-innovation.s3.us-west-2.amazonaws.com/demo-405/405-prepared-statement-0307.jpg)

### Step 2. Using batch inserts

+ Then, we will compare the performance of batch inserts and single inserts. On the left **EXPLORER** of the VS Code, under folder `mysql_connector_python_demo`, click `batch_insert.py` file,

+ In this step, we will insert 1000 rows into the table `t1_batchtest`. In the batch insert function `_batch_style_insert`, we will use the `executemany` function to insert the data. On the other hand, we will insert the data row by row using the `execute` function in the single insert function `_single_style_insert`.

  ```bash
  poetry run python mysql_connector_python_demo/batch_insert.py
  ```

  ```output
  Batch Inserting 1000 rows in 84.9921875 (ms).
  Total rows in t1_batchtest table: 1000.
  Non-Batch Inserting 1000 rows in 19608.541259765625 (ms).
  Total rows in t1_batchtest table: 1000.
  ```

![90%](https://public-pingcap-innovation.s3.us-west-2.amazonaws.com/demo-405/405-batch-insert-0307.jpg)

+ As you can see, the batch insert is much faster than the single insert.
