在 Visual C# 中无法连接到 MySql 服务器

Unable to connect to MySql Server in Visual C#

我正在尝试在 Visual C# 中使用 MySql 创建一个本地数据库,但是在代码中没有建立连接,但是当我在数据连接下的服务器资源管理器中添加服务器时,它正在工作。我试过测试连接它说连接成功但它在代码中不起作用。

string connStr = "server=localhost;user=root;database=entry_database;password=superadmin";
con = new SqlConnection(connStr);

这会抛出一个错误

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)

您的连接字符串错误.. 将键 "user" 更改为 "Uid",将 "password" 更改为 "Pwd"。

关注例如:

string connStr = "server=localhost;Uid=root;database=entry_database;Pwd=superadmin";

con = new SqlConnection(connStr);

您不能使用 SqlConnection class 连接到 MySQL 服务器;仅适用于 Microsoft SQL 服务器。

相反,安装 MySqlConnector NuGet 包并使用以下代码:

string connStr = "server=localhost;user=root;database=entry_database;password=superadmin";
using (var con = new MySqlConnection(connStr))
{
    // ...
}

正确,您创建连接字符串的格式不正确,导致您出现上述错误。

实际上,连接字符串在MS-SQL中的写法与MY-SQL有很大不同。每个数据库都有自己的连接方式和连接标签:-

请在下面找到 MS_SQL 的连接详细信息列表。这不仅可以帮助您解决当前提到的场景,还可以为将来的更改提供参考:-

https://www.connectionstrings.com/mysql/