Connect C# to Mysql database

。_饼干妹妹 提交于 2020-01-15 23:37:11

问题


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

A first chance exception of type 'System.ArgumentException' occurred in System.Data.dll

error.

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;
            }
        }

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;

I also tried connectig through gui but with no luck. Ideas ?

Edit 1 : with either connection string my program is still not working.

Edit 2 : OpenConnection method added.

Edit 3 : This is the error i get !


回答1:


p.s.

http://www.connectionstrings.com/mysql

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

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.




回答2:


Look here: http://www.connectionstrings.com/mysql Have all.




回答3:


Server=myServerAddress;Port=1234;Database=myDataBase;Uid=myUsername;Pwd=myPassword;

I think the problem is your database server:

Server=xxx.no-ip.org

It seems your app doesn't find the server. Check firewall.

You can debug and set an interruption point and check which exception it's throwing, not just the number



来源:https://stackoverflow.com/questions/12185296/connect-c-sharp-to-mysql-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!