## 模块 3：使用预处理语句和批量插入

现在，您可以使用 Python 代码读写 TiDB Cloud Starter 集群中的数据。但如果您想提高应用程序的性能，可以使用预处理语句（用于预编译和重复执行）和高效的批量插入（用于在单个 SQL 语句中向表中插入多行数据）。

### 步骤 1. 使用预处理语句

+ 在 VS Code 左侧的 **EXPLORER** 中，在 `mysql_connector_python_demo` 文件夹下，点击 `prepared_statement.py` 文件，查看示例代码中的 `connection.cursor(prepared=True)` 和 `print("Generated PK is", cursor.lastrowid)` 行。如果您使用参数 `prepared=False` 创建游标，则只使用客户端预处理语句。`cursor.lastrowid` 用于获取最近插入行的自动随机 ID。

+ 运行 `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)

### 步骤 2. 使用批量插入

+ 然后，我们将比较批量插入和单行插入的性能。在 VS Code 左侧的 **EXPLORER** 中，在 `mysql_connector_python_demo` 文件夹下，点击 `batch_insert.py` 文件。

+ 在这一步中，我们将向表 `t1_batchtest` 插入 1000 行数据。在批量插入函数 `_batch_style_insert` 中，我们将使用 `executemany` 函数插入数据。另一方面，我们将在单行插入函数 `_single_style_insert` 中使用 `execute` 函数逐行插入数据。

  ```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)

+ 这里我们可以看到，批量插入比单行插入快得多。
