【问题标题】:Cannot connect to MySQL Server and have no idea why [duplicate]无法连接到 MySQL 服务器并且不知道为什么 [重复]
【发布时间】:2020-11-22 06:59:04
【问题描述】:

我正在尝试连接到 MySQL 服务器

来自 MySQL Workbench 的屏幕截图:

using System;
using System.Data.SqlClient;

namespace C_sharp_test
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                string connectionString = "server=localhost;uid=root;pwd=***********;database=terra_incognita_online";
                SqlConnection sqlConnection = new SqlConnection();
                sqlConnection.ConnectionString = connectionString;
                sqlConnection.Open();
                Console.WriteLine("open");
                sqlConnection.Close();
                Console.WriteLine("close");
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
    }
}

我收到此错误

System.Data.SqlClient.SqlException (0x80131904): 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. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)

我不知道该怎么办,请帮忙

【问题讨论】:

    标签: c# mysql sql ado.net


    【解决方案1】:

    将“SqlConnection”替换为“MySqlConnection”即可。

     namespace C_sharp_test
     {
        class Program
        {
            static void Main(string[] args)
            {
               try
               {
                   string connectionString = "server=localhost;uid=root;pwd=***********;database=terra_incognita_online";
                   MySqlConnection sqlConnection = new MySqlConnection();
                   sqlConnection.ConnectionString = connectionString;
                   sqlConnection.Open();
                   Console.WriteLine("open");
                   sqlConnection.Close();
                   Console.WriteLine("close");
               }
               catch (Exception e)
               {
                   Console.WriteLine(e);
               }
           }
       }
    }
    

    另外,安装nuget包MySql.Data;

    并添加参考

     using MySql.Data.MySqlClient;
    

    【讨论】:

      【解决方案2】:

      您正在尝试使用用于 SQL Server 的类连接到 MySQL 数据库服务器。他们使用不同的协议,所以这是行不通的(几乎可以肯定永远不会)。

      如果您想使用 MySQL 而不是 SQL Server,请查看 MySQL connector for .NET

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-10-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-10-11
        • 2014-05-04
        相关资源
        最近更新 更多