Skip to content

Commit

Permalink
Preview PR pingcap/docs#14544 and this preview is triggered from commit
Browse files Browse the repository at this point in the history
  • Loading branch information
github-actions committed Aug 24, 2023
1 parent 8b025c6 commit f4f3bf0
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 28 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -219,6 +219,7 @@ with get_connection(autocommit=True) as connection:
For complete examples in Python, see:

- [Use PyMySQL to build a simple CRUD app with TiDB and Python](/develop/dev-guide-sample-application-python-pymysql.md#step-2-get-the-code)
- [Connecting to TiDB cluster with mysqlclient](https://github.com/tidb-samples/tidb-python-mysqlclient-quickstart)
- [Use MySQL Connector/Python to build a simple CRUD app with TiDB and Python](/develop/dev-guide-sample-application-python-mysql-connector.md#step-2-get-the-code)
- [Use SQLAlchemy to build a simple CRUD app with TiDB and Python](/develop/dev-guide-sample-application-python-sqlalchemy.md#step-2-get-the-code)
- [Use peewee to build a simple CRUD app with TiDB and Python](/develop/dev-guide-sample-application-python-peewee.md#step-2-get-the-code)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,17 +8,17 @@ summary: Learn how to connect TiDB using mysqlclient. This tutorial gives Python

# Connect TiDB with mysqlclient

TiDB is a MySQL compatible database. And [mysqlclient](https://github.com/PyMySQL/mysqlclient) is a popular open-source driver for Python.
TiDB is a MySQL-compatible database, and [mysqlclient](https://github.com/PyMySQL/mysqlclient) is a popular open-source driver for Python.

In this tutorial, use TiDB and mysqlclient to complete the following tasks:
In this tutorial, you can learn how to use TiDB and mysqlclient to accomplish the following tasks:

- Prepare your environment.
- Connect to TiDB Serverless, TiDB Dedicated or TiDB Self-Hosted using mysqlclient.
- Build and run your app. Optionally, you can find sample code snippets for basic CRUD operations.
- Set up your environment.
- Connect to your TiDB cluster using mysqlclient.
- Build and run your application. Optionally, you can find sample code snippets for basic CRUD operations.

> **Note:**
>
> This tutorial works with TiDB Serverless, TiDB Dedicated and TiDB Self-Hosted.
> This tutorial works with TiDB Serverless, TiDB Dedicated, and TiDB Self-Hosted.
## Prerequisites

Expand Down Expand Up @@ -51,22 +51,22 @@ This section demonstrates how to run the sample application code and connect to

### Step 1: Clone the sample app repository

Run the following command in your terminal window to clone the sample code repository.
Run the following command in your terminal window to clone the sample code repository:

```bash
```shell
git clone https://github.com/tidb-samples/tidb-python-mysqlclient-quickstart.git
cd tidb-python-mysqlclient-quickstart;
```

### Step 2: Install dependencies (including mysqlclient)

Run the following commands to install required packages for the sample app.
Run the following commands to install the required packages for the sample app:

```bash
```shell
pip install -r requirements.txt
```

If you encounter installation issues, please refer to the [mysqlclient official documentation](https://github.com/PyMySQL/mysqlclient#install).
If you encounter installation issues, refer to the [mysqlclient official documentation](https://github.com/PyMySQL/mysqlclient#install).

### Step 3: Configure connection information

Expand All @@ -75,7 +75,7 @@ Connect to your TiDB cluster depending on the TiDB deployment option you've sele
<SimpleTab>
<div label="TiDB Serverless">

1. Navigate to the [Clusters](https://tidbcloud.com/console/clusters) page on TiDB Cloud's Web Console, and then click the name of your target cluster to go to its **Overview** page.
1. Navigate to the [Clusters](https://tidbcloud.com/console/clusters) page on the TiDB Cloud console, and then click the name of your target cluster to go to its **Overview** page.

2. Click **Connect** in the upper-right corner. A connection dialog is displayed.

Expand All @@ -97,11 +97,11 @@ Connect to your TiDB cluster depending on the TiDB deployment option you've sele
5. Run the following command to copy `.env.example` and rename it to `.env`:

```bash
```shell
cp .env.example .env
```

6. Copy and paste the corresponding connection string into the `.env` file. Example result is as follows:
6. Copy and paste the corresponding connection string into the `.env` file. The example result is as follows:

```dotenv
TIDB_HOST='{gateway-region}.aws.tidbcloud.com'
Expand All @@ -121,21 +121,21 @@ Connect to your TiDB cluster depending on the TiDB deployment option you've sele
</div>
<div label="TiDB Dedicated">
1. Navigate to the [Clusters](https://tidbcloud.com/console/clusters) page on TiDB Cloud's Web Console, and then click the name of your target cluster to go to its **Overview** page.
1. Navigate to the [Clusters](https://tidbcloud.com/console/clusters) page on the TiDB Cloud console, and then click the name of your target cluster to go to its **Overview** page.
2. Click **Connect** in the upper-right corner. A connection dialog is displayed.
3. Click **Allow Access from Anywhere** and then click **Download TiDB cluster CA** to download the CA certificate.
> For more details about how to obtain the connection string, refer to [TiDB Dedicated Standard Connection](https://docs.pingcap.com/tidbcloud/connect-via-standard-connection).
For more details about how to obtain the connection string, refer to [TiDB Dedicated Standard Connection](https://docs.pingcap.com/tidbcloud/connect-via-standard-connection).
4. Run the following command to copy `.env.example` and rename it to `.env`:
```bash
```shell
cp .env.example .env
```
5. Copy and paste the corresponding connection string into the `.env` file. Example result is as follows:
5. Copy and paste the corresponding connection string into the `.env` file. The example result is as follows:
```dotenv
TIDB_HOST='{host}.clusters.tidb-cloud.com'
Expand All @@ -146,7 +146,7 @@ Connect to your TiDB cluster depending on the TiDB deployment option you've sele
CA_PATH='{your-downloaded-ca-path}'
```
Be sure to replace the placeholders `{}` with the values obtained from the **Connect** window, and configure `CA_PATH` with the certificate path downloaded in the previous step.
Be sure to replace the placeholders `{}` with the values obtained from the connection dialog, and configure `CA_PATH` with the certificate path downloaded in the previous step.
6. Save the `.env` file.
Expand All @@ -155,11 +155,11 @@ Connect to your TiDB cluster depending on the TiDB deployment option you've sele
1. Run the following command to copy `.env.example` and rename it to `.env`:
```bash
```shell
cp .env.example .env
```
2. Copy and paste the corresponding connection string into the `.env` file. Example result is as follows:
2. Copy and paste the corresponding connection string into the `.env` file. The example result is as follows:
```dotenv
TIDB_HOST='{tidb_server_host}'
Expand All @@ -176,11 +176,21 @@ Connect to your TiDB cluster depending on the TiDB deployment option you've sele
</div>
</SimpleTab>
### Step 4: Run the code and check the result
1. Execute the following command to run the sample code:
```shell
python mysqlclient_example.py
```
2. Check the [Expected output.txt](https://github.com/tidb-samples/tidb-python-mysqlclient-quickstart/blob/main/Expected-Output.txt) to see if the output matches.
## Sample code snippets
You can refer to the following sample code snippets to complete your own application development.
For complete code and how to run it, see the [tidb-python-mysqlclient-quickstart GitHub repository](https://github.com/tidb-samples/tidb-python-mysqlclient-quickstart).
For complete sample code and how to run it, check out the [tidb-samples/tidb-python-mysqlclient-quickstart](https://github.com/tidb-samples/tidb-python-mysqlclient-quickstart) repository.
### Connect to TiDB
Expand Down Expand Up @@ -232,7 +242,10 @@ For more information, refer to [Query Data](/develop/dev-guide-get-data-from-sin
with get_mysqlclient_connection(autocommit=True) as conn:
with conn.cursor() as cur:
player_id, amount, price="1", 10, 500
cursor.execute("UPDATE players SET goods = goods + %s, coins = coins + %s WHERE id = %s", (-amount, price, player_id))
cursor.execute(
"UPDATE players SET goods = goods + %s, coins = coins + %s WHERE id = %s",
(-amount, price, player_id),
)
```
For more information, refer to [Update Data](/develop/dev-guide-update-data.md).
Expand All @@ -250,12 +263,25 @@ For more information, refer to [Update Data](/develop/dev-guide-delete-data.md).
## Useful notes
### Using Driver or ORM?
### Using driver or ORM framework?
This Python driver is relatively low-level, so you will see a lot of SQL statements in the sample app. Unlike ORMs, there is no data object, and `mysqlclient` represents query objects with tuples. Although Python's driver is more convenient to use than those in other languages, due to its exposure to underlying implementations and the manual transaction management required, it is still recommended to use ORMs for programming unless there is a significant need for SQL. This can reduce the coupling of your app.
The Python driver provides low-level access to the database, but it also requires the developers to:
- Establish and release database connections manually.
- Manage database transactions manually.
- Map data rows (represented as tuples in the `mysqlclient`) to data objects manually.
Unless you need to write complex SQL statements, it is recommended to use [ORMs](https://en.wikipedia.org/w/index.php?title=Object%E2%80%93relational_mapping) for developing. They can help you:
- Reduce [boilerplate code](https://en.wikipedia.org/wiki/Boilerplate_code) for managing connections and transactions.
- Manipulate data with data objects instead of an amount of SQL statements.
## Next steps
- If you want to learn more on how to use `mysqlclient`, refer to the [mysqlclient official documentation](https://mysqlclient.readthedocs.io/).
- You can continue reading the developer documentation to get more knowledge about TiDB development, such as: [Insert Data](/develop/dev-guide-insert-data.md), [Update Data](/develop/dev-guide-update-data.md), [Delete Data](/develop/dev-guide-delete-data.md), [Single Table Reading](/develop/dev-guide-get-data-from-single-table.md), [Transactions](/develop/dev-guide-transaction-overview.md), [SQL Performance Optimization](/develop/dev-guide-optimize-sql-overview.md), etc.
- If you prefer to learn through courses, we also offer professional [TiDB Developer Courses](https://www.pingcap.com/education/), and provide [TiDB certifications](https://www.pingcap.com/education/certification/) after the exam.
- Learn more usage of `mysqlclient` from [the documentation of mysqlclient](https://mysqlclient.readthedocs.io/)
- Learn the best practices for TiDB application development with the chapters in the [Developer Guide](/develop/dev-guide-overview.md), such as: [Insert Data](/develop/dev-guide-insert-data.md), [Update Data](/develop/dev-guide-update-data.md), [Delete Data](/develop/dev-guide-delete-data.md), [Single Table Reading](/develop/dev-guide-get-data-from-single-table.md), [Transactions](/develop/dev-guide-transaction-overview.md), [SQL Performance Optimization](/develop/dev-guide-optimize-sql-overview.md), etc.
- Learn through the professional [TiDB Developer Courses](https://www.pingcap.com/education/) and earn [TiDB certifications](https://www.pingcap.com/education/certification/) after passing the exam.
## Need help?
Ask questions on the TiDB [Forum](https://ask.pingcap.com/) or [Discord](https://discord.com/channels/1083300679386406923/channel-browser), or get help from the [TiDB Cloud support team](https://tidbcloud.com/console/support).

0 comments on commit f4f3bf0

Please sign in to comment.