将C#连接到Mysql数据库 [英] Connect C# to Mysql database
问题描述
我想从C#连接到mysql服务器。我在网上发现了一些代码,但在某处有错误,因为我得到
I want to connect to mysql server from C#. I found some code on the net but somewhere there is something wrong because i get
发生类型'System.ArgumentException'的第一次机会异常在System.Data.dll
A first chance exception of type 'System.ArgumentException' occurred in System.Data.dll
错误。
private void Initialise()
{
server = "dns to server";
database = "db_name";
uid = "root";
password = "password";
string connectionString;
connectionString = "SERVER=" + server + ";" + "DATABASE=" +
database + ";" + "UID=" +
uid + ";" + "PASSWORD=" + password + ";";
OR
connectionString = "Server=xxx.no-ip.org;Database=rdb;"+
"Uid=root;Pwd=wHt2%Zt;";
connection = new MySqlConnection(connectionString);
if (this.OpenConnection() == true)
Console.Out.Write("SUCCESS");
else
Console.Out.Write("ERROR");
}
private bool OpenConnection() {
try {
connection.Open();
return true;
}
catch (MySqlException ex){
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;
}
}
我在控制台上没有收到任何消息。我添加了 Mysql.Data
作为我的项目的引用,我使用使用MySql.Data.MySqlClient;
I don't get any message on the console. I added Mysql.Data
as a reference to my project and i used using MySql.Data.MySqlClient;
我也试过connectig通过gui,但没有运气。想要吗?
I also tried connectig through gui but with no luck. Ideas ?
编辑1:使用任一连接字符串我的程序仍然无法工作。
Edit 1 : with either connection string my program is still not working.
编辑2:OpenConnection方法。
Edit 2 : OpenConnection method added.
编辑3:这是我得到的错误! / a>
Edit 3 : This is the error i get !
推荐答案
ps
http://www.connectionstrings.com/mysql
您可能需要更改你的方法...使用webconfig或应用程序配置来设置和读取你的连接串从配置...
probably you need to change your approach...use a webconfig or app config to setup and read your connectionstrings from the config...
我也建议你阅读这个.. 。
I would also recommend you to read this...
http://www.codeproject.com/Articles/12300/An-ASP-NET-Application-Using-a-MySQL-Database
UPDATE
根据您更新的结果...可能有两个问题,先检查您的连接字符串,以检查用户root是否具有所需的权限。
Based on your updated findings...there can be two problems, first double check your connectionstring, Second is to check if the user "root" has the required permissions.
这篇关于将C#连接到Mysql数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!