我尝试连接到我的Windows应用程序中的mysql数据库,但是我一直遇到MySQLException,它与Open Connection中的case 0有关。一切都应该是正确的。可能是我对服务器的名称有误,但它应该只是localhost。我在哪里可以检查服务器名称是否正确,如果是,还有什么可能导致此问题?
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace PlantsClientServerApp
{
public partial class AllPlants : Form
{
private string server;
private string database;
private string uid;
private string password;
private MySqlConnection connection;
private MySqlDataAdapter mySqlDataAdapter;
public AllPlants()
{
InitializeComponent();
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Hide();
}
private void AllPlants_Load(object sender, EventArgs e)
{
server = "localhost";
database = "plants only";
uid = "root";
password = "K1326629ktcj5423";
string connectionString;
connectionString = "SERVER=" + server + ";" + "DATABASE=" + database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
connection = new MySqlConnection(connectionString);
if (this.OpenConnection() == true)
{
mySqlDataAdapter = new MySqlDataAdapter("select * from plants_database2", connection);
DataSet DS = new DataSet();
mySqlDataAdapter.Fill(DS);
dataGridView1.DataSource = DS.Tables[0];
//close connection
this.CloseConnection();
}
}
private bool OpenConnection()
{
try
{
connection.Open();
return true;
}
catch (MySqlException ex)
{
//When handling errors, you can your application's response based on the error number.
//The two most common error numbers when connecting are as follows:
//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;
default:
MessageBox.Show(ex.Message);
break;
}
return false;
}
}
private bool CloseConnection()
{
try
{
connection.Close();
return true;
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message);
return false;
}
}
}
}