Can't connect to MySQL database due to KeyNotFoundException

2.2k Views Asked by At

Not sure why I get an error every single time i try to connect. I tried so many things. When i type the wrong password while connecting manually it says access not granted or whatever so I know it connects but when it connects I get this weird error.

An unhandled exception of type 'System.Collections.Generic.KeyNotFoundException' occurred in mscorlib.dll Additional information: The given key was not present in the dictionary.

For localhost it works when I have this connection string.

server=localhost; port=3306; USER ID=root; password=***; database=database;

but when I change the server user id and password it decides to not work.

The exception is thrown at cn.Open();

     private void button1_Click(object sender, EventArgs e)
    {
        MySqlConnection cn = new MySqlConnection();
        cn.ConnectionString = "server=db4free.net ;port=3306; 
                               user=goof; password=pwd; database=s;";
        cn.Open();
        MySqlCommand cmd = new MySqlCommand("select * from users where
                                             username = '" 
                                             + textBox1.Text + "',
                                             and password = '" 
                                             + textBox2.Text + "'", cn);
        MySqlDataReader dr;
        dr = cmd.ExecuteReader();
        int count = 0;

        while(dr.Read())
        {
            count += 1;
        }
        if(count == 1)
        {
            MessageBox.Show("success");
        }
        else
        {
            MessageBox.Show("error");
        }
    }
2

There are 2 best solutions below

0
pijemcolu On

The problem is the user=goof field should be user id=goof.

Change your connection string into this:

cn.ConnectionString = "server=db4free.net ;port=3306; USER ID=goof; password=pwd; database=s;";
1
Olfredos6 On

try using "user id" or "uid" instead of just "user" and let us know if its does the job!