Question

I have an WPF application that reads data from a file like so:

foreach (String line in File.ReadAllLines(file, Encoding.UTF8))
{}

Each line is then parsed and displayed on the screen which all works fine. Some of the data has cyrillic alphabet in it and the strings that I'm using to store this data in are also displayed fine on the screen in the app window.

However, after that I'm using those same strings to insert them into MySQL database. I'm building a query and firing it up MySqlCommand cmd = new MySqlCommand(query, conn); which successfully inserts a new line in the database with the appropriate information. Numbers are all fine, however all the strings that go into the database and have cyrillic letters are displayed as ????????

Database engine is InnoDB and the encoding of the table and all varchar fields in it is utf_general_ci so any idea what is going on and how can I save the correct string in the database?

EDIT: Per request, here's some code. Database connection:

    conn = new MySqlConnection();
    conn.ConnectionString = "//censored//";

And the file reading / db loading, shortened for the purposes of this code snippet:

foreach (String line in File.ReadAllLines(file, Encoding.UTF8))
{
      string[] tokens = line.Split('|');
      string query = "INSERT INTO myTable SET first_name = '" + tokens[0] + "'" + ", last_name = '" + tokens[1] + "'";
      MessageBox.Show(tokens[0]);
      MySqlCommand cmd = new MySqlCommand(query, conn);
      cmd.ExecuteNonQuery();
}

The message box shows the name as it should be but what goes into the database is ???????.

Was it helpful?

Solution

After some headbanging I did figure out where the problem is so posting an answer for all to see:

The key part is the way you establish your connection to the database:

conn.ConnectionString = @"Server = YOURSERVER; Database = YOURDB; Uid = YOURUSER ; Pwd = 'YOURPASSWORD'; charset=utf8;";

I was missing the charset=utf8; part before so I assume all kinds of non-utf8 junk was going to the database regardless of the fact that I was encoding in UTF8 on both sides of the connection. Hope this helps!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top