Connect to TiDB with node-mysql2

TiDB is a MySQL-compatible database, and node-mysql2 is a fast mysqljs/mysql compatible MySQL driver for Node.js.

In this tutorial, you can learn how to use TiDB and node-mysql2 to accomplish the following tasks:

  • Set up your environment.
  • Connect to your TiDB cluster using node-mysql2.
  • Build and run your application. Optionally, you can find sample code snippets for basic CRUD operations.

node-mysql2 - 图1

Note

This tutorial works with TiDB Serverless, TiDB Dedicated, and TiDB Self-Hosted.

Prerequisites

To complete this tutorial, you need:

  • Node.js >= 16.x installed on your machine.
  • Git installed on your machine.
  • A TiDB cluster running.

If you don’t have a TiDB cluster, you can create one as follows:

Run the sample app to connect to TiDB

This section demonstrates how to run the sample application code and connect to TiDB.

Step 1: Clone the sample app repository

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

  1. git clone https://github.com/tidb-samples/tidb-nodejs-mysql2-quickstart.git
  2. cd tidb-nodejs-mysql2-quickstart

Step 2: Install dependencies

Run the following command to install the required packages (including mysql2 and dotenv) for the sample app:

  1. npm install

Install dependencies to existing project

For your existing project, run the following command to install the packages:

  1. npm install mysql2 dotenv --save

Step 3: Configure connection information

Connect to your TiDB cluster depending on the TiDB deployment option you’ve selected.

  • TiDB Serverless
  • TiDB Dedicated
  • TiDB Self-Hosted
  1. Navigate to the Clusters page, 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. Ensure the configurations in the connection dialog match your operating environment.

    • Endpoint Type is set to Public.
    • Branch is set to main.
    • Connect With is set to General.
    • Operating System matches the operating system where you run the application.
  4. If you have not set a password yet, click Generate Password to generate a random password.

  5. Run the following command to copy .env.example and rename it to .env:

    1. cp .env.example .env
  6. Edit the .env file, set up the environment variables as follows, replace the corresponding placeholders {} with connection parameters on the connection dialog:

    1. TIDB_HOST={host}
    2. TIDB_PORT=4000
    3. TIDB_USER={user}
    4. TIDB_PASSWORD={password}
    5. TIDB_DATABASE=test
    6. TIDB_ENABLE_SSL=true

    node-mysql2 - 图2

    Note

    For TiDB Serverless, TLS connection MUST be enabled via TIDB_ENABLE_SSL when using public endpoint.

  7. Save the .env file.

  8. Navigate to the Clusters page, and then click the name of your target cluster to go to its overview page.

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

  10. Click Allow Access from Anywhere and then click Download CA cert to download the CA certificate.

    For more details about how to obtain the connection string, refer to TiDB Dedicated standard connection.

  11. Run the following command to copy .env.example and rename it to .env:

    1. cp .env.example .env
  12. Edit the .env file, set up the environment variables as follows, replace the corresponding placeholders {} with connection parameters on the connection dialog:

    1. TIDB_HOST={host}
    2. TIDB_PORT=4000
    3. TIDB_USER={user}
    4. TIDB_PASSWORD={password}
    5. TIDB_DATABASE=test
    6. TIDB_ENABLE_SSL=true
    7. TIDB_CA_PATH={downloaded_ssl_ca_path}

    node-mysql2 - 图3

    Note

    It is recommended to enable TLS connection when using the public endpoint to connect to TiDB Dedicated.

    To enable TLS connection, modify TIDB_ENABLE_SSL to true and using TIDB_CA_PATH to specify the file path of CA certificate downloaded from the connection dialog.

  13. Save the .env file.

  14. Run the following command to copy .env.example and rename it to .env:

    1. cp .env.example .env
  15. Edit the .env file, set up the environment variables as follows, replace the corresponding placeholders {} with connection parameters on the connection dialog:

    1. TIDB_HOST={host}
    2. TIDB_PORT=4000
    3. TIDB_USER=root
    4. TIDB_PASSWORD={password}
    5. TIDB_DATABASE=test

    If you are running TiDB locally, the default host address is 127.0.0.1, and the password is empty.

  16. Save the .env file.

Step 4: Run the code and check the result

Run the following command to execute the sample code:

  1. npm start

If the connection is successful, the console will output the version of the TiDB cluster as follows:

  1. 🔌 Connected to TiDB cluster! (TiDB version: 8.0.11-TiDB-v8.1.0)
  2. Loading sample game data...
  3. Loaded sample game data.
  4. 🆕 Created a new player with ID 12.
  5. ℹ️ Got Player 12: Player { id: 12, coins: 100, goods: 100 }
  6. 🔢 Added 50 coins and 50 goods to player 12, updated 1 row.
  7. 🚮 Deleted 1 player data.

Sample code snippets

You can refer to the following sample code snippets to complete your own application development.

For complete sample code and how to run it, check out the tidb-samples/tidb-nodejs-mysql2-quickstart repository.

Connect with connection options

The following code establishes a connection to TiDB with options defined in the environment variables:

  1. // Step 1. Import the 'mysql' and 'dotenv' packages.
  2. import { createConnection } from "mysql2/promise";
  3. import dotenv from "dotenv";
  4. import * as fs from "fs";
  5. // Step 2. Load environment variables from .env file to process.env.
  6. dotenv.config();
  7. async function main() {
  8. // Step 3. Create a connection to the TiDB cluster.
  9. const options = {
  10. host: process.env.TIDB_HOST || '127.0.0.1',
  11. port: process.env.TIDB_PORT || 4000,
  12. user: process.env.TIDB_USER || 'root',
  13. password: process.env.TIDB_PASSWORD || '',
  14. database: process.env.TIDB_DATABASE || 'test',
  15. ssl: process.env.TIDB_ENABLE_SSL === 'true' ? {
  16. minVersion: 'TLSv1.2',
  17. ca: process.env.TIDB_CA_PATH ? fs.readFileSync(process.env.TIDB_CA_PATH) : undefined
  18. } : null,
  19. }
  20. const conn = await createConnection(options);
  21. // Step 4. Perform some SQL operations...
  22. // Step 5. Close the connection.
  23. await conn.end();
  24. }
  25. void main();

node-mysql2 - 图4

Note

For TiDB Serverless, you MUST enable TLS connection via TIDB_ENABLE_SSL when using public endpoint. However, you don’t have to specify an SSL CA certificate via TIDB_CA_PATH, because Node.js uses the built-in Mozilla CA certificate by default, which is trusted by TiDB Serverless.

Insert data

The following query creates a single Player record and returns a ResultSetHeader object:

  1. const [rsh] = await conn.query('INSERT INTO players (coins, goods) VALUES (?, ?);', [100, 100]);
  2. console.log(rsh.insertId);

For more information, refer to Insert data.

Query data

The following query returns a single Player record by ID 1:

  1. const [rows] = await conn.query('SELECT id, coins, goods FROM players WHERE id = ?;', [1]);
  2. console.log(rows[0]);

For more information, refer to Query data.

Update data

The following query adds 50 coins and 50 goods to the Player with ID 1:

  1. const [rsh] = await conn.query(
  2. 'UPDATE players SET coins = coins + ?, goods = goods + ? WHERE id = ?;',
  3. [50, 50, 1]
  4. );
  5. console.log(rsh.affectedRows);

For more information, refer to Update data.

Delete data

The following query deletes the Player record with ID 1:

  1. const [rsh] = await conn.query('DELETE FROM players WHERE id = ?;', [1]);
  2. console.log(rsh.affectedRows);

For more information, refer to Delete data.

Useful notes

  • Using connection pools to manage database connections can reduce the performance overhead caused by frequently establishing and destroying connections.
  • To avoid SQL injection, it is recommended to use prepared statements.
  • In scenarios where there are not many complex SQL statements involved, using ORM frameworks like Sequelize, TypeORM, or Prisma can greatly improve development efficiency.
  • It is recommended to enable the supportBigNumbers: true option when dealing with big numbers (BIGINT and DECIMAL columns) in the database.
  • It is recommended to enable the enableKeepAlive: true option to avoid socket error read ECONNRESET due to network problems. (Related issue: sidorares/node-mysql2#683)

Next steps

Need help?

Ask questions on the Discord, or create a support ticket.

Ask questions on the Discord, or create a support ticket.