如何正确连接 MySQL 数据库和 C# 应用程序?

Moe*_*eez 6 c# mysql ado.net azure

我正在尝试连接我的MySQL数据库,C#但它没有连接。

我在用

static string connstring = @"server=my.live.ip;userid=user;password=123;database=db_name;port=3306";
Run Code Online (Sandbox Code Playgroud)

但我仍然得到

使用方法 'mysql_native_password' 对用户 'user' 的主机 'my.live.ip' 进行身份验证失败并显示消息:用户 'user'@'202.xxx.xxx.xxx' 访问被拒绝(使用密码:否)`

我已经对其进行了搜索,但没有找到任何合适的解决方案。

PS:live IP我使用的是azure。即MySQL数据库通过托管在 azure 服务器上xampp

任何帮助将不胜感激

小智 0

using System;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;
namespace AzureMySqlExample
{
class MySqlCreate
{
    static async Task Main(string[] args)
    {
        var builder = new MySqlConnectionStringBuilder
        {
            Server = "YOUR-SERVER.mysql.database.azure.com",
            Database = "YOUR-DATABASE",
            UserID = "USER@YOUR-SERVER",
            Password = "PASSWORD",
            SslMode = MySqlSslMode.Required,
        };

        using (var conn = new MySqlConnection(builder.ConnectionString))
        {
            Console.WriteLine("Opening connection");
            await conn.OpenAsync();

            using (var command = conn.CreateCommand())
            {
                command.CommandText = "DROP TABLE IF EXISTS inventory;";
                await command.ExecuteNonQueryAsync();
                Console.WriteLine("Finished dropping table (if existed)");

                command.CommandText = "CREATE TABLE inventory (id serial PRIMARY KEY, name VARCHAR(50), quantity INTEGER);";
                await command.ExecuteNonQueryAsync();
                Console.WriteLine("Finished creating table");

                command.CommandText = @"INSERT INTO inventory (name, quantity) VALUES (@name1, @quantity1),
                    (@name2, @quantity2), (@name3, @quantity3);";
                command.Parameters.AddWithValue("@name1", "banana");
                command.Parameters.AddWithValue("@quantity1", 150);
                command.Parameters.AddWithValue("@name2", "orange");
                command.Parameters.AddWithValue("@quantity2", 154);
                command.Parameters.AddWithValue("@name3", "apple");
                command.Parameters.AddWithValue("@quantity3", 100);

                int rowCount = await command.ExecuteNonQueryAsync();
                Console.WriteLine(String.Format("Number of rows inserted={0}", rowCount));
            }

            // connection will be closed by the 'using' block
            Console.WriteLine("Closing connection");
        }

        Console.WriteLine("Press RETURN to exit");
        Console.ReadLine();
    }
}
Run Code Online (Sandbox Code Playgroud)

}

  • 通常会解释为什么你的答案可以解决问题,而不是仅仅转储代码。 (2认同)