user3790180
user3790180

Reputation: 443

KeyNotFoundException on MySql Query / C#

I am developing a software on C#, I must use MySQL connection on this program. I can connect to database. Visual Studio is throwing a exception on ExecuteReader() line.

Exception: KeyNotFoundException , "The given key was not present in the dictionary"

This is my code:

MySqlConnectionStringBuilder bag = new MySqlConnectionStringBuilder();
        bag.Server = "localhost";
        bag.UserID = "root";
        bag.Password = "123456";
        bag.Database = "randevu_takip";
        MySqlConnection baglan = new MySqlConnection();
        baglan.ConnectionString = bag.ToString();
        baglan.Open();

 MySqlCommand komut = new MySqlCommand();
        komut.Connection = baglan;
        komut.CommandType = CommandType.Text;
        komut.CommandText = "SELECT * FROM kullanicilar;";

        MySqlDataReader oku = komut.ExecuteReader();

        while (oku.Read())
        {
            MessageBox.Show(oku.GetString("sifre"));
        }

Upvotes: 3

Views: 1987

Answers (2)

Shamim Shaikh
Shamim Shaikh

Reputation: 827

Stop MySql Server

Add / Edit below configuration in mysql config file, i.e. my.ini file Which is located in

C:\ProgramData\MySql\MySql Server [version]

[mysqld]
character-set-server=utf8
collation-server=utf8_general_ci

Start MySql Server

Upvotes: 0

user7286729
user7286729

Reputation:

The problem solved for me when I change my column Collation from utf8mb4_unicode_520_ci to utf8_general_ci.

Try to define same charset for connection and table.

var connection = new MySqlConnection("Server=localhost; Port=3307;  uid=your_name; Pwd=your_password; Database=your_database; charset=utf8;");

To change collation for tables you can use,

ALTER TABLE mytable CONVERT TO CHARACTER SET utf8

Upvotes: 1

Related Questions