gpt4 book ai didi

c# - 无法创建与 mySQL 的 C# 连接

转载 作者:行者123 更新时间:2023-11-30 22:34:01 25 4
gpt4 key购买 nike

好的,所以我正在尝试使用 C#/.NET 创建一个需要数据库的简单程序。我已经阅读了一些内容并尝试建立连接,但由于某种原因我的计算机无法连接到服务器(本地主机)。我已经在我的 PC 上成功安装了 MySQL Connector/NET 和 MySQL,我正在使用工作台创建数据库表。我的代码是:

 class DBconnect
{
private MySqlConnection connection;
private string server;
private string database;
private string uid;
private string password;

//Constructor
public DBconnect()
{
Initialize();
}

//Initialize values
private void Initialize()
{
server = "localhost";
database = "clientsdb";
uid = "root";
password = "password";
string connectionString;
connectionString = "SERVER=" + server + ";" + "DATABASE=" + database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
//connectionString = "datasource=" + server + ";port=3306;username=" + uid + ";password=" + password + ";";

connection = new MySqlConnection(connectionString);
}

//open connection to database
private bool OpenConnection()
{
try
{
connection.Open();
return true;
}
catch (MySqlException ex)
{
//0: Cannot connect to server.
//1045: Invalid user name and/or password.
switch (ex.Number)
{
case 0:
MessageBox.Show("Cannot connect to server. Contact administrator");
break;

case 1045:
MessageBox.Show("Invalid username/password, please try again");
break;
}
return false;
}
}

我已经尝试了两个“connectionString”-s,但是当我尝试使用 OpenConnection 函数时,它给了我无法连接到服务器的错误。我做错了什么?

最佳答案

使用 https://www.connectionstrings.com/mysql/我得到这样的连接字符串:

connectionString = "Server=" + server + ";" + "Database=" + database + ";" + "Uid=" + uid + ";" + "Pwd=" + password + ";";

哪个应该有效。

关于c# - 无法创建与 mySQL 的 C# 连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33055970/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com