title | summary |
---|---|
Connect to TiDB with GORM |
Learn how to connect to TiDB using GORM. This tutorial gives Golang sample code snippets that work with TiDB using 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.
Note:
This tutorial works with TiDB Cloud Serverless, TiDB Cloud Dedicated, and TiDB Self-Managed.
To complete this tutorial, you need:
If you don't have a TiDB cluster, you can create one as follows:
- (Recommended) Follow Creating a TiDB Cloud Serverless cluster to create your own TiDB Cloud cluster.
- Follow Deploy a local test TiDB cluster or Deploy a production TiDB cluster to create a local cluster.
If you don't have a TiDB cluster, you can create one as follows:
- (Recommended) Follow Creating a TiDB Cloud Serverless cluster to create your own TiDB Cloud cluster.
- Follow Deploy a local test TiDB cluster or Deploy a production TiDB cluster to create a local cluster.
This section demonstrates how to run the sample application code and connect to TiDB.
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
Connect to your TiDB cluster depending on the TiDB deployment option you've selected.
-
Navigate to the Clusters page, and then click the name of your target cluster to go to its overview page.
-
Click Connect in the upper-right corner. A connection dialog is displayed.
-
Ensure the configurations in the connection dialog match your operating environment.
- Connection Type is set to
Public
- Branch is set to
main
- Connect With is set to
General
- Operating System matches your environment.
Tip:
If your program is running in Windows Subsystem for Linux (WSL), switch to the corresponding Linux distribution.
- Connection Type is set to
-
Click Generate Password to create a random password.
Tip:
If you have created a password before, you can either use the original password or click Reset Password to generate a new one.
-
Run the following command to copy
.env.example
and rename it to.env
:cp .env.example .env
-
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 Cloud Serverless requires a secure connection. Therefore, you need to set the value of
USE_SSL
totrue
. -
Save the
.env
file.
-
Navigate to the Clusters page, and then click the name of your target cluster to go to its overview page.
-
Click Connect in the upper-right corner. A connection dialog is displayed.
-
In the connection dialog, select Public from the Connection Type drop-down list, and then click CA cert to download the CA certificate.
If you have not configured the IP access list, click Configure IP Access List or follow the steps in Configure an IP Access List to configure it before your first connection.
In addition to the Public connection type, TiDB Dedicated supports Private Endpoint and VPC Peering connection types. For more information, see Connect to Your TiDB Dedicated Cluster.
-
Run the following command to copy
.env.example
and rename it to.env
:cp .env.example .env
-
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. -
Save the
.env
file.
-
Run the following command to copy
.env.example
and rename it to.env
:cp .env.example .env
-
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 setUSE_SSL
tofalse
. If you are running TiDB locally, the default host address is127.0.0.1
, and the password is empty. -
Save the
.env
file.
-
Execute the following command to run the sample code:
make
-
Check the Expected-Output.txt to see if the output matches.
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.
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 Cloud Serverless requires a secure connection. Therefore, you need to set the value of ${use_ssl}
to true
.
db.Create(&Player{ID: "id", Coins: 1, Goods: 1})
For more information, refer to Insert data.
var queryPlayer Player
db.Find(&queryPlayer, "id = ?", "id")
For more information, refer to Query data.
db.Save(&Player{ID: "id", Coins: 100, Goods: 1})
For more information, refer to Update data.
db.Delete(&Player{ID: "id"})
For more information, refer to Delete data.
- Learn more usage of GORM from the documentation of GORM and the TiDB section in the documentation of GORM.
- Learn the best practices for TiDB application development with the chapters in the Developer guide, such as Insert data, Update data, Delete data, Single table reading, Transactions, and SQL performance optimization.
- Learn through the professional TiDB developer courses and earn TiDB certifications after passing the exam.
Ask the community on Discord or Slack, or submit a support ticket.
Ask the community on Discord or Slack, or submit a support ticket.