连接到本地 MySQL 服务器时出现问题

Problems connecting to local MySQL server

我在连接到本地 MySQL 数据库时遇到问题。

我确定服务器是 运行,我可以使用连接字符串中的用户名和密码连接到服务器,并使用终端创建数据库。

我在 mac 和 MySQL 8.0.16 上使用 visual studio 社区。

示例: Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace ReadSQL
{
    class Program
    {
        static void Main(string[] args)
        {
            DataAccess dataAccess = new DataAccess();
            dataAccess.GetTask();
        }
    }
}

DataAccess.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dapper;
using System.Data;

namespace ReadSQL
{
    public class DataAccess
    {
        public List<Task> GetTask()
        {
            using (IDbConnection connection = new System.Data.SqlClient.SqlConnection(Helper.CnnVal("workloadDB")))
            {
                var output = connection.Query<Task>($"select * from task where id=1").ToList(); //exception thrown here
                Console.WriteLine(output);           
            }
        }
     }
}

Helper.cs

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ReadSQL
{

        public static class Helper
        {
            public static string CnnVal(string name)
            {
                return ConfigurationManager.ConnectionStrings[name].ConnectionString;
            }
        } 
}

Task.cs

using System;
namespace ReadSQL
{
    public class Task
    {
        int id { get; set; }
        string name { get; set; }
    }
}

App.config

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <connectionStrings>
        <add name="workloadDB" connectionString="Server=localhost;Database=workload;Uid=root;Pwd=adminPasswort;" providerName="System.Data.SqlClient"/>
    </connectionStrings>
</configuration>

我希望变量输出包含我的 table 的第一行,但我却收到错误消息:

System.Data.SqlClient.SqlException A network-related or instance-specific error occurred while establishing a connection to sql server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections.

不知道为什么连接不上,因为MySQL服务器肯定是运行,连接字符串应该是正确的(也试过:trusted_connection=true ;). 提前致谢!

您不能使用 SqlConnection class 连接到 MySQL。相反,从 NuGet 安装 MySqlConnector,然后使用:

using (IDbConnection connection = new MySqlConnection(Helper.CnnVal("workloadDB")))
{
    var output = connection.Query<Task>($"select * from task where id=1").ToList();          
}

您的连接字符串看起来应该与 MySqlConnection 兼容,但如果您使用任何其他选项,您应该 double-check 它们与 the list of valid connection options.