首页 > 解决方案 > 无法连接到 MySQL 服务器并且不知道为什么

问题描述

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

MySQL Workbench 的屏幕截图:

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#mysqlsqlado.net

解决方案


将“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;

推荐阅读