Connect to TiDB with Go-MySQL-Driver

TiDB is a MySQL-compatible database, and Go-MySQL-Driver is a MySQL implementation for the database/sql interface.

In this tutorial, you can learn how to use TiDB and Go-MySQL-Driver to accomplish the following tasks:

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

Go-MySQL-Driver - 图1

Note

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

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:

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-golang-sql-driver-quickstart.git
  2. cd tidb-golang-sql-driver-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.

    Go-MySQL-Driver - 图2

    Tip

    If your program is running in Windows Subsystem for Linux (WSL), switch to the corresponding Linux distribution.

  4. Click Generate Password to create a random password.

    Go-MySQL-Driver - 图3

    Tip

    If you have created a password before, you can either use the original password or click Reset Password to generate a new one.

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

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

    1. TIDB_HOST='{host}' # e.g. gateway01.ap-northeast-1.prod.aws.tidbcloud.com
    2. TIDB_PORT='4000'
    3. TIDB_USER='{user}' # e.g. xxxxxx.root
    4. TIDB_PASSWORD='{password}'
    5. TIDB_DB_NAME='test'
    6. 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.

  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. Copy and paste the corresponding connection string into the .env file. The example result is as follows:

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

    Be sure to replace the placeholders {} with the connection parameters obtained 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. Copy and paste the corresponding connection string into the .env file. The example result is as follows:

    1. TIDB_HOST='{host}'
    2. TIDB_PORT='4000'
    3. TIDB_USER='root'
    4. TIDB_PASSWORD='{password}'
    5. TIDB_DB_NAME='test'
    6. 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.

  16. Save the .env file.

Step 3: Run the code and check the result

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

    1. 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-sql-driver-quickstart repository.

Connect to TiDB

  1. func openDB(driverName string, runnable func(db *sql.DB)) {
  2. dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&tls=%s",
  3. ${tidb_user}, ${tidb_password}, ${tidb_host}, ${tidb_port}, ${tidb_db_name}, ${use_ssl})
  4. db, err := sql.Open(driverName, dsn)
  5. if err != nil {
  6. panic(err)
  7. }
  8. defer db.Close()
  9. runnable(db)
  10. }

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

  1. openDB("mysql", func(db *sql.DB) {
  2. insertSQL = "INSERT INTO player (id, coins, goods) VALUES (?, ?, ?)"
  3. _, err := db.Exec(insertSQL, "id", 1, 1)
  4. if err != nil {
  5. panic(err)
  6. }
  7. })

For more information, refer to Insert data.

Query data

  1. openDB("mysql", func(db *sql.DB) {
  2. selectSQL = "SELECT id, coins, goods FROM player WHERE id = ?"
  3. rows, err := db.Query(selectSQL, "id")
  4. if err != nil {
  5. panic(err)
  6. }
  7. // This line is extremely important!
  8. defer rows.Close()
  9. id, coins, goods := "", 0, 0
  10. if rows.Next() {
  11. err = rows.Scan(&id, &coins, &goods)
  12. if err == nil {
  13. fmt.Printf("player id: %s, coins: %d, goods: %d\n", id, coins, goods)
  14. }
  15. }
  16. })

For more information, refer to Query data.

Update data

  1. openDB("mysql", func(db *sql.DB) {
  2. updateSQL = "UPDATE player set goods = goods + ?, coins = coins + ? WHERE id = ?"
  3. _, err := db.Exec(updateSQL, 1, -1, "id")
  4. if err != nil {
  5. panic(err)
  6. }
  7. })

For more information, refer to Update data.

Delete data

  1. openDB("mysql", func(db *sql.DB) {
  2. deleteSQL = "DELETE FROM player WHERE id=?"
  3. _, err := db.Exec(deleteSQL, "id")
  4. if err != nil {
  5. panic(err)
  6. }
  7. })

For more information, refer to Delete data.

Useful notes

Using driver or ORM framework?

The Golang driver provides low-level access to the database, but it requires the developers to:

  • Manually establish and release database connections.
  • Manually manage database transactions.
  • Manually map data rows to data objects.

Unless you need to write complex SQL statements, it is recommended to use ORM framework for development, such as GORM. It can help you:

  • Reduce boilerplate code for managing connections and transactions.
  • Manipulate data with data objects instead of a number of SQL statements.

Next steps

Need help?

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