C# (macOS)

更新时间:
复制 MD 格式

AnalyticDB for MySQL supports using C# in Visual Studio for Mac to connect to AnalyticDB for MySQL.

Prerequisites

  • Download and install Visual Studio for Mac. This topic was tested with Visual Studio for Mac version 8.6.5.

  • Prepare test data in the AnalyticDB for MySQL database as described in the Get started with Data Warehouse Edition topic.

    create table t1 (a int, s1 varchar)DISTRIBUTED BY HASH(`a`) ENGINE='XUANWU';
    insert into t1 values (11, 'test1'), (22, 'test2'), (33, 'test3'), (44, 'test4');
    create user test identified by 'test_123456';
    grant select on test.* to test;

Procedure

  1. Start Visual Studio.

  2. Choose Run > File, and then click Create Solution.

  3. Enter a project name as prompted by the system to create a sample project named hello world. Then, click Solution in the upper-left corner. The system displays the execution result.Example

  4. Replace the default code with the following code to connect to AnalyticDB for MySQL and print the data from the t1 table.

    using System;
    using MySql.Data.MySqlClient;
    namespace connectADB
    {
        class Program
        {
            static void Main(string[] args)
            {
                string connStr = "server=127.0.0.1;UID=test;database=test;port=3306;password=test_123456;SslMode=none;";
                MySqlConnection conn = new MySqlConnection(connStr);
                try
                {
                    Console.WriteLine("Connecting to MySQL...");
                    conn.Open();
                    string sql = "select * from `t1`";
                    MySqlCommand cmd = new MySqlCommand(sql, conn);
                    MySqlDataReader rdr = cmd.ExecuteReader();
                    while (rdr.Read())
                    {
                        Console.WriteLine(rdr[0] + " --- " + rdr[1]);
                    }
                    rdr.Close();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
                conn.Close();
                Console.WriteLine("Done.");
            }
        }
    }

    After you modify the code, an error message appears, prompting you to import the MySqlConnector package.

  5. Right-click Next, and select Manage NuGet Package.

    Note

    Connecting to AnalyticDB for MySQL with C# requires the MySqlConnector package.

  6. On the Manage NuGet Package page, enter MySqlConnector in the search box, and then click Add Package.

  7. After the MySqlConnector package is successfully added, the error message disappears. Click Running in the upper-left corner, and the system outputs the correct result.