Connect to TiDB with GORM

TiDB is a MySQL-compatible database, and GORM is a popular open-source ORM framework for Golang. GORM adapts to TiDB features such as AUTO_RANDOM and supports TiDB as a default database option.

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

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

Prerequisites

To complete this tutorial, you need:

  • Go 1.20 or higher.
  • Git.
  • A TiDB cluster.

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:

git clone https://github.com/tidb-samples/tidb-golang-gorm-quickstart.git cd tidb-golang-gorm-quickstart

Step 2: 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 your environment.
  4. Click Generate Password to create a random password.

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

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

    TIDB_HOST='{host}' # e.g. gateway01.ap-northeast-1.prod.aws.tidbcloud.com TIDB_PORT='4000' TIDB_USER='{user}' # e.g. xxxxxx.root TIDB_PASSWORD='{password}' TIDB_DB_NAME='test' USE_SSL='true'

    Be sure to replace the placeholders {} with the connection parameters obtained from the connection dialog.

    TiDB Serverless requires a secure connection. Therefore, you need to set the value of USE_SSL to true.

  7. Save the .env file.

  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. 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.

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

    cp .env.example .env
  5. Copy and paste the corresponding connection string into the .env file. The example result is as follows:

    TIDB_HOST='{host}' # e.g. tidb.xxxx.clusters.tidb-cloud.com TIDB_PORT='4000' TIDB_USER='{user}' # e.g. root TIDB_PASSWORD='{password}' TIDB_DB_NAME='test' USE_SSL='false'

    Be sure to replace the placeholders {} with the connection parameters obtained from the connection dialog.

  6. Save the .env file.

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

    cp .env.example .env
  2. Copy and paste the corresponding connection string into the .env file. The example result is as follows:

    TIDB_HOST='{host}' TIDB_PORT='4000' TIDB_USER='root' TIDB_PASSWORD='{password}' TIDB_DB_NAME='test' USE_SSL='false'

    Be sure to replace the placeholders {} with the connection parameters, and set USE_SSL to false. If you are running TiDB locally, the default host address is 127.0.0.1, and the password is empty.

  3. Save the .env file.

Step 3: Run the code and check the result

  1. Execute the following command to run the sample code:

    make
  2. Check the 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 sample code and how to run it, check out the tidb-samples/tidb-golang-gorm-quickstart repository.

Connect to TiDB

func createDB() *gorm.DB { dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&tls=%s", ${tidb_user}, ${tidb_password}, ${tidb_host}, ${tidb_port}, ${tidb_db_name}, ${use_ssl}) db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{ Logger: logger.Default.LogMode(logger.Info), }) if err != nil { panic(err) } return db }

When using this function, you need to replace ${tidb_host}, ${tidb_port}, ${tidb_user}, ${tidb_password}, and ${tidb_db_name} with the actual values of your TiDB cluster. TiDB Serverless requires a secure connection. Therefore, you need to set the value of ${use_ssl} to true.

Insert data

db.Create(&Player{ID: "id", Coins: 1, Goods: 1})

For more information, refer to Insert data.

Query data

var queryPlayer Player db.Find(&queryPlayer, "id = ?", "id")

For more information, refer to Query data.

Update data

db.Save(&Player{ID: "id", Coins: 100, Goods: 1})

For more information, refer to Update data.

Delete data

db.Delete(&Player{ID: "id"})

For more information, refer to Delete data.

Next steps

Need help?

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