flipis
flipis

Reputation: 251

Inserting diacritic characters into MySQL database

I have MySQL database with table MySqlTable which is encoded utf8_slovak_ci and I'd like to INSERT strings with diacritics chars(ľščťžýáí...) typical for slovak language via C# code.

I'm using MySql.Data.MySqlClient namespace for allowing MySql objects. My C# method:

    public void Insert(string sqlQuery, params string[] strings) 
    {
        MySqlCommand command = new MySqlCommand(sqlQuery, connection);

        for (int i = 0; i < strings.Length; i++)
        {
            command.Parameters.Add(new MySqlParameter("@str" + i, strings[i]));
        }

        try
        {
            connection.Open();
            command.ExecuteNonQuery();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "Chyba!", MessageBoxButton.OK, MessageBoxImage.Error);
        }
        finally 
        {
            connection.Close();
        }
    }

Calling this method from program:

database.Insert(query, newEmployee.Name);

where query is

string query = @"INSERT INTO MySqlTable(name) " +
                        "VALUES(@str0)";

Where is the problem... When I try to insert some string icluding that special characters (f.e. Anča), it is saved like Anca in the database. But when I execute corresponding INSERT query via phpmyadmin, it is saved properly. Problem chars are just ľčťďň (saved like lctdn), other chars like šžýáíéúäô are saved OK. Anybody knows where could be a problem? Thank you

Upvotes: 2

Views: 2065

Answers (2)

honzakuzel1989
honzakuzel1989

Reputation: 2520

Equivalent for mysql command line tools is --default-character-set parameter. For example:

mysql -h host -u user -ppass --default-character-set=utf8
mysql> source make_db.sql 

where make_db.sql is sql script in utf (with diacritics).

Upvotes: 2

harry
harry

Reputation: 156

In the connection string specify "charset=utf8;". For example: "Datasource=192.168.48.128;Database=something;uid=user;pwd=password;charset=utf8;"

And of course set the charset of the table to utf-8 and the collation to the slovak variant.

Worked for hungarian language.

Credits: read/write unicode data in MySql

Upvotes: 3

Related Questions