我在连接mysql和C#程序时有点麻烦。我已经安装了Mysql连接器dot net ver 8.0.12。我可以从phpmyadmin和mysql工作台访问数据库。所以我做了一个简单的代码,使用C#程序连接数据库。这是我的代码:
using System;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace TryMySQL
{
public partial class Form1 : Form
{
private MySqlConnection connection;
private string server;
private string port;
private string database;
private string uid;
private string password;
public Form1()
{
InitializeComponent();
try
{
Initialize();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void Initialize()
{
server = "127.0.0.1";
port = "3306";
database = "testdb";
uid = "root";
password = "123456789";
string connectionString;
connectionString = "datasource=" + server + ";" + "port=" + port + ";" + "database=" +
database + ";" + "username=" + uid + ";" + "password=" + password + ";";
connection = new MySqlConnection(connectionString);
}
//open connection to database
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;
}
return false;
}
}
}
}
我怎么了?我认为我只是做正确的事。对于这种情况,需要更多建议。