好的,所以我试图用C#/ .NET创建一个需要数据库的简单程序。我已经阅读了一些内容并尝试建立连接,但出于某种原因,我的计算机无法连接到服务器(localhost)。我已经在我的PC上成功安装了MySQL Connector / NET和MySQL,我使用workbench来创建数据库表。我的代码是:
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函数时,它让我无法连接到服务器错误。我做错了什么?
答案 0 :(得分:0)
使用https://www.connectionstrings.com/mysql/我得到一个像这样的连接字符串:
connectionString = "Server=" + server + ";" + "Database=" + database + ";" + "Uid=" + uid + ";" + "Pwd=" + password + ";";
应该有用。