Skip to content

Add C# / .NET example #21206

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
Open

Add C# / .NET example #21206

wants to merge 7 commits into from

Conversation

dveeden
Copy link
Contributor

@dveeden dveeden commented Jun 19, 2025

What is changed, added or deleted? (Required)

Add example with C#

Which TiDB version(s) do your changes apply to? (Required)

Tips for choosing the affected version(s):

By default, CHOOSE MASTER ONLY so your changes will be applied to the next TiDB major or minor releases. If your PR involves a product feature behavior change or a compatibility change, CHOOSE THE AFFECTED RELEASE BRANCH(ES) AND MASTER.

For details, see tips for choosing the affected versions.

  • master (the latest development version)
  • v9.0 (TiDB 9.0 versions)
  • v8.5 (TiDB 8.5 versions)
  • v8.4 (TiDB 8.4 versions)
  • v8.3 (TiDB 8.3 versions)
  • v8.1 (TiDB 8.1 versions)
  • v7.5 (TiDB 7.5 versions)
  • v7.1 (TiDB 7.1 versions)
  • v6.5 (TiDB 6.5 versions)
  • v6.1 (TiDB 6.1 versions)
  • v5.4 (TiDB 5.4 versions)

What is the related PR or file link(s)?

  • This PR is translated from:
  • Other reference link(s):

Do your changes match any of the following descriptions?

  • Delete files
  • Change aliases
  • Need modification after applied to another branch
  • Might cause conflicts after applied to another branch

@ti-chi-bot ti-chi-bot bot added area/develop This PR relates to the area of TiDB App development. missing-translation-status This PR does not have translation status info. size/L Denotes a PR that changes 100-499 lines, ignoring generated files. labels Jun 19, 2025
Copy link

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Summary of Changes

Hello @dveeden, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request expands the TiDB documentation by adding a new guide and code example for connecting to TiDB using C# and the .NET framework. The primary objective is to provide clear instructions and a practical sample for developers looking to integrate C# applications with TiDB, highlighting its compatibility with the MySQL protocol.

Highlights

  • New C#/.NET Example: This pull request introduces a comprehensive new documentation page (develop/dev-guide-sample-application-cs.md) that provides a step-by-step guide for connecting C# applications to TiDB. It covers project setup, dependency management using NuGet (MySql.Data), and includes a functional C# code sample.
  • Documentation Integration: The newly added C# example is integrated into the existing documentation structure by updating the Table of Contents files (TOC-tidb-cloud.md and TOC.md). This ensures the new content is discoverable and accessible to users browsing the documentation.
  • MySQL Compatibility Demonstration: The C# example explicitly leverages TiDB's MySQL compatibility by using the standard MySql.Data connector for .NET, demonstrating how existing MySQL client libraries can be used to interact with TiDB.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point in your pull request via creating an issue comment (i.e. comment on the pull request page) using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in issue comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist is currently in preview and may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments to provide feedback.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

@dveeden dveeden requested review from mjonss, Icemap, hfxsd and Oreoxmt June 19, 2025 15:32
Copy link

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request adds a C# example for connecting to TiDB. The documentation is well-structured and provides a good starting point for .NET developers. The review includes suggestions to enhance code robustness and adhere more closely to the style guide. The changes to TOC files are correct.

The review comments reference the following aspects of the style guide:

  • General Writing Principles:
    • Use of second person ("you") (Style Guide ref: lines 22-22).
    • Correct grammar, spelling, and punctuation (Style Guide ref: lines 20-20, 55-57).
  • Structure and Format:
    • Sentence case for headings (Style Guide ref: lines 32-32).

Comment on lines 74 to 97
MySqlConnection conn = new MySqlConnection(connStr);
try
{
Console.WriteLine("Connecting to TiDB...\n");
conn.Open();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}

Console.WriteLine("Connected to: " + conn.ServerVersion);

MySqlCommand cmd = new MySqlCommand("SELECT TIDB_VERSION()", conn);

MySqlDataReader rdr = cmd.ExecuteReader();

rdr.Read();
Console.WriteLine("\nVersion details:\n" + rdr[0]);
rdr.Close();

conn.Close();
Console.WriteLine("Done.");
}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The current C# code for connecting and querying can be made more robust and idiomatic:

  1. Error Handling: If conn.Open() fails, the subsequent lines attempting to use conn (e.g., conn.ServerVersion, cmd.ExecuteReader()) will throw further exceptions. The logic dependent on a successful connection should be within the try block or protected by a check.
  2. Resource Management: MySqlConnection, MySqlCommand, and MySqlDataReader are IDisposable. Using using statements ensures they are correctly disposed of, even if errors occur. This also handles closing the connection and reader automatically.
  3. DataReader Check: It's good practice to check the return value of rdr.Read() before trying to access data.

Here's a revised version of the Main method body (excluding connStr initialization for brevity in this comment, but included in the suggestion) that incorporates these improvements:

        // Using 'using' for MySqlConnection ensures it's disposed correctly.
        using (MySqlConnection conn = new MySqlConnection(connStr))
        {
            try
            {
                Console.WriteLine("Connecting to TiDB...\n");
                conn.Open();
                Console.WriteLine("Successfully connected!"); // Added for clarity

                Console.WriteLine("Connected to TiDB version: " + conn.ServerVersion);

                // 'using' for MySqlCommand and MySqlDataReader ensures they are disposed.
                using (MySqlCommand cmd = new MySqlCommand("SELECT TIDB_VERSION()", conn))
                using (MySqlDataReader rdr = cmd.ExecuteReader())
                {
                    if (rdr.Read()) // Check if there is data to read
                    {
                        Console.WriteLine("\nTiDB specific version details:\n" + rdr[0]);
                    }
                    else
                    {
                        Console.WriteLine("\nCould not retrieve TiDB specific version details.");
                    }
                    // rdr.Close() is handled by the 'using' statement's Dispose()
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("An error occurred:");
                Console.WriteLine(ex.ToString());
            }
            // conn.Close() is handled by the 'using' statement's Dispose()
        }
        Console.WriteLine("Done.");
    }

{
public static void Main()
{
string connStr = "server=127.0.0.1;user=root;database=test;port=4000";

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

low

The example connection string is good for a local tiup playground setup. It might be helpful to briefly remind users about password security for production or self-hosted environments beyond tiup playground. Also, for general MySQL compatibility, especially if user-defined variables might be used in other queries, AllowUserVariables=true can be useful, though not strictly required for this specific example.

Suggested change
string connStr = "server=127.0.0.1;user=root;database=test;port=4000";
string connStr = "server=127.0.0.1;user=root;database=test;port=4000;AllowUserVariables=true"; // For production, always use strong, unique passwords.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This makes the line too long. Maybe the comment should be on the line above?

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You are absolutely right, dveeden! My apologies for the oversight regarding line length. Placing the comment on the same line as the connection string can indeed make it exceed readability limits, especially in documentation where code examples should be clean and easy to follow.

Moving the comment to a separate line above the connStr declaration is a much better approach for readability and adherence to common style guides. This keeps the line length manageable while still providing the important context about password security and the AllowUserVariables=true option for broader MySQL compatibility.

Thank you for pointing this out!

Suggested change
string connStr = "server=127.0.0.1;user=root;database=test;port=4000";
// For production, always use strong, unique passwords.
string connStr = "server=127.0.0.1;user=root;database=test;port=4000;AllowUserVariables=true";

@hfxsd hfxsd self-assigned this Jun 20, 2025
@hfxsd hfxsd added translation/doing This PR's assignee is translating this PR. and removed missing-translation-status This PR does not have translation status info. labels Jun 20, 2025
Copy link

ti-chi-bot bot commented Jun 20, 2025

[APPROVALNOTIFIER] This PR is NOT APPROVED

This pull-request has been approved by:
Once this PR has been reviewed and has the lgtm label, please ask for approval from hfxsd. For more information see the Code Review Process.
Please ensure that each of them provides their approval before proceeding.

The full list of commands accepted by this bot can be found here.

Needs approval from an approver in each of these files:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment

@lilin90 lilin90 removed the request for review from Oreoxmt June 20, 2025 03:43
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
---
title: Connect to TiDB with C#
summary: Learn how to connect to TiDB using C#. This tutorial gives C# sample code snippets that work with TiDB.
aliases: ['/tidb/dev/sample-application-cs','/tidb/dev/dev-guide-sample-application-cs']
Copy link
Collaborator

@hfxsd hfxsd Jun 23, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
aliases: ['/tidb/dev/sample-application-cs','/tidb/dev/dev-guide-sample-application-cs']

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@hfxsd this doesn't make any actual changes?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry, deleted.

dveeden and others added 3 commits June 23, 2025 11:14
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
area/develop This PR relates to the area of TiDB App development. size/L Denotes a PR that changes 100-499 lines, ignoring generated files. translation/doing This PR's assignee is translating this PR.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants