Connect to an AnalyticDB for MySQL cluster from a macOS machine using C# and Visual Studio for Mac.
Prerequisites
Before you begin, ensure that you have:
Visual Studio for Mac installed (this guide uses Visual Studio 2019 for Mac version 8.6.5)
Test data prepared in your AnalyticDB for MySQL cluster — see Getting started with Data Warehouse Edition
To prepare the test data used in this guide, run the following SQL statements in your cluster:
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;Connect to AnalyticDB for MySQL
Step 1: Create a project
Open Visual Studio for Mac.
Go to File > New Solution. In the New Project dialog box, select Console Application and click Next.
Name the project (for example,
hello world).Click the Execute icon in the upper-left corner to confirm the project runs successfully.
Step 2: Add the connection code
Replace the default code in your project with the following:
using System;
using MySql.Data.MySqlClient;
namespace connectADB
{
class Program
{
static void Main(string[] args)
{
string connStr = "server=<host>;UID=<username>;database=<database>;port=<port>;password=<password>;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.");
}
}
}Replace the placeholders in the connection string with your actual values:
| Placeholder | Description | Where to find it |
|---|---|---|
<host> | Cluster endpoint | AnalyticDB for MySQL console > Cluster Information |
<username> | Database username | The user you created (e.g., test) |
<database> | Database name | The database you want to connect to (e.g., test) |
<port> | Connection port | AnalyticDB for MySQL console > Cluster Information (default: 3306) |
<password> | User password | The password set when creating the user |
Step 3: Install the MySqlConnector package
After adding the connection code, Visual Studio reports an error because the MySqlConnector NuGet package is missing.
Right-click Solution in the Solution Explorer and select Manage NuGet Package.
Search for
MySqlConnectorand click Add Package
Step 4: Run the project
Click the Execute icon in the upper-left corner. If the connection succeeds, the console displays the rows from the t1 table.