使用 Go-MySQL-Driver 连接到 TiDB

TiDB 是一个兼容 MySQL 的数据库。Go-MySQL-Driver 是 database/sql 接口的 MySQL 实现。

本文档将展示如何使用 TiDB 和 Go-MySQL-Driver 来完成以下任务:

  • 配置你的环境。
  • 使用 Go-MySQL-Driver 连接到 TiDB 集群。
  • 构建并运行你的应用程序。你也可以参考示例代码片段,完成基本的 CRUD 操作。

Go-MySQL-Driver - 图1

注意

本文档适用于 TiDB Serverless、TiDB Dedicated 和本地部署的 TiDB。

前置需求

运行代码并连接到 TiDB

本小节演示如何运行示例应用程序的代码,并连接到 TiDB。

第 1 步:克隆示例代码仓库到本地

运行以下命令,将示例代码仓库克隆到本地:

1. git clone https://github.com/tidb-samples/tidb-golang-sql-driver-quickstart.git
2. cd tidb-golang-sql-driver-quickstart

第 2 步:配置连接信息

根据不同的 TiDB 部署方式,使用不同的方法连接到 TiDB 集群。

  • TiDB Serverless
  • TiDB Dedicated
  • 本地部署 TiDB

  • 在 TiDB Cloud 的 Clusters 页面中,选择你的 TiDB Serverless 集群,进入集群的 Overview 页面。

  • 点击右上角的 Connect 按钮,将会弹出连接对话框。
  • 确认对话框中的配置和你的运行环境一致。

  • Endpoint Type 为 Public。

  • Branch 选择 main。
  • Connect With 选择 General。
  • Operating System 为你的运行环境。

Go-MySQL-Driver - 图2

小贴士

如果你在 Windows Subsystem for Linux (WSL) 中运行,请切换为对应的 Linux 发行版。 4. 如果你还没有设置密码,点击 Generate Password 生成一个随机密码。

Go-MySQL-Driver - 图3

小贴士

如果你之前已经生成过密码,可以直接使用原密码,或点击 Reset Password 重新生成密码。 5. 运行以下命令,将 .env.example 复制并重命名为 .env:

1. cp .env.example .env 6. 复制并粘贴对应连接字符串至 .env 中。示例结果如下:

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'

注意替换 {} 中的占位符为连接对话框中获得的值。

TiDB Serverless 要求使用 TLS (SSL) connection,因此 USE_SSL 的值应为 true。 7. 保存 .env 文件。 8. 在 TiDB Cloud 的 Clusters 页面中,选择你的 TiDB Dedicated 集群,进入集群的 Overview 页面。 9. 点击右上角的 Connect 按钮,将会出现连接对话框。 10. 在对话框中点击 Allow Access from Anywhere。

更多配置细节,可参考 [TiDB Dedicated 标准连接教程(英文)](https://docs.pingcap.com/tidbcloud/connect-via-standard-connection)。
  1. 运行以下命令,将 .env.example 复制并重命名为 .env:

    1. cp .env.example .env 12. 复制并粘贴对应的连接字符串至 .env 中。示例结果如下:

    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'

    注意替换 {} 中的占位符为连接对话框中获得的值。 13. 保存 .env 文件。 14. 运行以下命令,将 .env.example 复制并重命名为 .env:

    1. cp .env.example .env 15. 复制并粘贴对应 TiDB 的连接字符串至 .env 中。示例结果如下:

    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'

    注意替换 {} 中的占位符为你的 TiDB 对应的值,并设置 USE_SSL 为 false。如果你在本机运行 TiDB,默认 Host 地址为 127.0.0.1,密码为空。 16. 保存 .env 文件。

第 3 步:运行代码并查看结果

  1. 运行下述命令,执行示例代码:

1. make 2. 查看 Expected-Output.txt,并与你的程序输出进行比较。结果近似即为连接成功。

示例代码片段

你可参考以下关键代码片段,完成自己的应用开发。

完整代码及其运行方式,见代码仓库 tidb-golang-sql-driver-quickstart。

连接到 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()

10. runnable(db)
11. }

在使用该函数时,你需要将 ${tidb_host}、${tidb_port}、${tidb_user}、${tidb_password}、${tidb_db_name} 等替换为你的 TiDB 集群的实际值。因为 TiDB Serverless 要求使用 TLS (SSL) connection,因此在连接到 TiDB Serverless 时 ${use_ssl} 的值应为 true。

插入数据

1. openDB("mysql", func(db *sql.DB) {
2. insertSQL := "INSERT INTO player (id, coins, goods) VALUES (?, ?, ?)"
3. _, err := db.Exec(insertSQL, "id", 1, 1)

5. if err != nil {
6. panic(err)
7. }
8. })

更多信息参考插入数据。

查询数据

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

8. // This line is extremely important!
9. defer rows.Close()

11. id, coins, goods := "", 0, 0
12. if rows.Next() {
13. err = rows.Scan(&id, &coins, &goods)
14. if err == nil {
15. fmt.Printf("player id: %s, coins: %d, goods: %d\n", id, coins, goods)
16. }
17. }
18. })

更多信息参考查询数据。

更新数据

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")

5. if err != nil {
6. panic(err)
7. }
8. })

更多信息参考更新数据。

删除数据

1. openDB("mysql", func(db *sql.DB) {
2. deleteSQL := "DELETE FROM player WHERE id=?"
3. _, err := db.Exec(deleteSQL, "id")

5. if err != nil {
6. panic(err)
7. }
8. })

更多信息参考删除数据。

注意事项

使用驱动程序还是 ORM 框架?

Golang 驱动程序提供对数据库的底层访问,但要求开发者:

  • 手动建立和释放数据库连接
  • 手动管理数据库事务
  • 手动将数据行映射为数据对象

建议仅在需要编写复杂的 SQL 语句时使用驱动程序。其他情况下,建议使用 ORM 框架进行开发,例如 GORM。ORM 可以帮助你:

  • 减少管理连接和事务的模板代码
  • 使用数据对象代替大量 SQL 语句来操作数据

下一步

需要帮助?

如果在开发的过程中遇到问题,可以在 AskTUG 上进行提问,寻求帮助。