|
| 1 | +--- |
| 2 | +title: 使用 C# 连接 TiDB |
| 3 | +summary: 了解如何使用 C# 连接 TiDB。本教程提供了与 TiDB 交互的 C# 代码示例。 |
| 4 | +--- |
| 5 | + |
| 6 | +# 使用 C\# 连接 TiDB |
| 7 | + |
| 8 | +C#(发音为 "C-Sharp")是 .NET 技术体系中的一种编程语言,由微软开发。其他 .NET 语言还包括 VB.NET 和 F#。在本文档中,你将使用 C# 和 MySQL Connector/NET,通过 MySQL 协议将 C# 应用程序连接到 TiDB。这种连接方式可行,是因为 TiDB [与 MySQL 高度兼容](/mysql-compatibility.md)。 |
| 9 | + |
| 10 | +虽然 .NET 通常用于 Windows 操作系统,但它同样适用于 macOS 和 Linux 系统。在不同平台上,相关命令和代码基本一致,仅在提示符和文件路径上存在细微差别。 |
| 11 | + |
| 12 | +## 前提条件 |
| 13 | + |
| 14 | +- 下载并安装 [.NET 9.0 SDK](https://dotnet.microsoft.com/en-us/download)。 |
| 15 | +- 本教程使用 `dotnet` 命令行工具,你也可以使用 Visual Studio Code IDE 编写和运行 C# 代码。 |
| 16 | +- 你需要有一个可用的 TiDB 实例。可以使用 [{{{ .starter }}}](https://docs.pingcap.com/tidbcloud/select-cluster-tier/#tidb-cloud-serverless) 或 [TiDB Cloud Dedicated](https://docs.pingcap.com/tidbcloud/select-cluster-tier/#tidb-cloud-dedicated) 集群,或自托管的 TiDB 集群(如通过 `tiup playground` 启动的集群)。 |
| 17 | + |
| 18 | +## 第 1 步:创建控制台项目 |
| 19 | + |
| 20 | +使用 `console` 模板创建一个新项目。以下命令会生成一个名为 `tidb_cs` 的新目录。在运行以下命令前,请先切换到希望创建该目录的位置,或指定完整路径。 |
| 21 | + |
| 22 | +``` |
| 23 | +$ dotnet new console -o tidb_cs |
| 24 | +The template "Console App" was created successfully. |
| 25 | +
|
| 26 | +Processing post-creation actions... |
| 27 | +Restoring /home/dvaneeden/tidb_cs/tidb_cs.csproj: |
| 28 | +Restore succeeded. |
| 29 | +``` |
| 30 | + |
| 31 | +## 第 2 步:添加 MySql.Data 包 |
| 32 | + |
| 33 | +.NET 的包管理器是 NuGet。MySQL Connector/NET 在 NuGet 上的包名为 [MySql.Data](https://www.nuget.org/packages/MySql.Data),它为 .NET 应用提供对 MySQL 协议的支持。如果你未指定版本,NuGet 会安装最新稳定版(如 9.3.0)。 |
| 34 | + |
| 35 | +```shell |
| 36 | +$ cd tidb_cs |
| 37 | +$ dotnet add package MySql.Data |
| 38 | + |
| 39 | +Build succeeded in 1.0s |
| 40 | +info : X.509 certificate chain validation will use the system certificate bundle at '/etc/pki/ca-trust/extracted/pem/objsign-ca-bundle.pem'。 |
| 41 | +info : X.509 certificate chain validation will use the fallback certificate bundle at '/usr/lib64/dotnet/sdk/9.0.106/trustedroots/timestampctl.pem'。 |
| 42 | +info : Adding PackageReference for package 'MySql.Data' into project '/home/dvaneeden/tidb_cs/tidb_cs.csproj'。 |
| 43 | +info : GET https://api.nuget.org/v3/registration5-gz-semver2/mysql.data/index.json |
| 44 | +info : OK https://api.nuget.org/v3/registration5-gz-semver2/mysql.data/index.json 133ms |
| 45 | +info : Restoring packages for /home/dvaneeden/tidb_cs/tidb_cs.csproj... |
| 46 | +info : GET https://api.nuget.org/v3/vulnerabilities/index.json |
| 47 | +info : OK https://api.nuget.org/v3/vulnerabilities/index.json 98ms |
| 48 | +info : GET https://api.nuget.org/v3-vulnerabilities/2025.06.18.05.40.02/vulnerability.base.json |
| 49 | +info : GET https://api.nuget.org/v3-vulnerabilities/2025.06.18.05.40.02/2025.06.19.11.40.05/vulnerability.update.json |
| 50 | +info : OK https://api.nuget.org/v3-vulnerabilities/2025.06.18.05.40.02/vulnerability.base.json 32ms |
| 51 | +info : OK https://api.nuget.org/v3-vulnerabilities/2025.06.18.05.40.02/2025.06.19.11.40.05/vulnerability.update.json 64ms |
| 52 | +info : Package 'MySql.Data' is compatible with all the specified frameworks in project '/home/dvaneeden/tidb_cs/tidb_cs.csproj'。 |
| 53 | +info : PackageReference for package 'MySql.Data' version '9.3.0' added to file '/home/dvaneeden/tidb_cs/tidb_cs.csproj'。 |
| 54 | +info : Generating MSBuild file /home/dvaneeden/tidb_cs/obj/tidb_cs.csproj.nuget.g.targets。 |
| 55 | +info : Writing assets file to disk. Path: /home/dvaneeden/tidb_cs/obj/project.assets.json |
| 56 | +log : Restored /home/dvaneeden/tidb_cs/tidb_cs.csproj (in 551 ms)。 |
| 57 | +``` |
| 58 | + |
| 59 | +## 第 3 步:更新代码 |
| 60 | + |
| 61 | +将 `Program.cs` 中的 "Hello World" 示例替换为以下代码: |
| 62 | + |
| 63 | +```cs |
| 64 | +using System; |
| 65 | +using MySql.Data.MySqlClient; |
| 66 | +public class Tutorial1 |
| 67 | +{ |
| 68 | + public static void Main() |
| 69 | + { |
| 70 | + // 生产环境请务必使用强密码和唯一密码。 |
| 71 | + string connStr = "server=127.0.0.1;user=root;database=test;port=4000;AllowUserVariables=true"; |
| 72 | + MySqlConnection conn = new MySqlConnection(connStr); |
| 73 | + try |
| 74 | + { |
| 75 | + Console.WriteLine("Connecting to TiDB...\n"); |
| 76 | + conn.Open(); |
| 77 | + } |
| 78 | + catch (Exception ex) |
| 79 | + { |
| 80 | + Console.WriteLine(ex.ToString()); |
| 81 | + Environment.Exit(1); |
| 82 | + } |
| 83 | + |
| 84 | + Console.WriteLine("Connected to: " + conn.ServerVersion); |
| 85 | + |
| 86 | + MySqlCommand cmd = new MySqlCommand("SELECT TIDB_VERSION()", conn); |
| 87 | + |
| 88 | + MySqlDataReader rdr = cmd.ExecuteReader(); |
| 89 | + |
| 90 | + rdr.Read(); |
| 91 | + Console.WriteLine("\nVersion details:\n" + rdr[0]); |
| 92 | + rdr.Close(); |
| 93 | + |
| 94 | + conn.Close(); |
| 95 | + Console.WriteLine("Done."); |
| 96 | + } |
| 97 | +} |
| 98 | +``` |
| 99 | + |
| 100 | +该代码会连接到指定 IP 和端口的 TiDB 实例。如果你使用的是 TiDB Cloud,请将连接字符串中的参数(如主机名、端口、用户名和密码)替换为 [TiDB Cloud 控制台](https://tidbcloud.com/)提供的信息。 |
| 101 | + |
| 102 | +代码首先会连接数据库,并打印其版本信息,然后执行 [`TIDB_VERSION()`](/functions-and-operators/tidb-functions.md#tidb_version) 查询以获取更详细的版本信息,最后输出结果。 |
| 103 | + |
| 104 | +## 第 4 步:运行程序 |
| 105 | + |
| 106 | +``` |
| 107 | +$ dotnet run |
| 108 | +Connecting to TiDB... |
| 109 | +
|
| 110 | +Connected to: 8.0.11-TiDB-v8.5.2 |
| 111 | +
|
| 112 | +Version details: |
| 113 | +Release Version: v8.5.2 |
| 114 | +Edition: Community |
| 115 | +Git Commit Hash: f43a13324440f92209e2a9f04c0bbe9cf763978d |
| 116 | +Git Branch: HEAD |
| 117 | +UTC Build Time: 2025-05-29 03:30:55 |
| 118 | +GoVersion: go1.23.8 |
| 119 | +Race Enabled: false |
| 120 | +Check Table Before Drop: false |
| 121 | +Store: tikv |
| 122 | +Done. |
| 123 | +``` |
0 commit comments