Reputation: 767
I am writing a program in C# that's using a sqlite database (throug ADO, System.Data.SQLite).
The problem is that when I insert strings from my c# app containing Swedish or German characters (åäöüÅÄÖÜ etc) they are stored incorrectly in the db. (looking like ö and ä ect), but if I insert them directly to the db using SQLite Administrator they are saved correctly.
Furthermore, when I try to retrieve data with my C# app that is stored correctly, it's messed up in the same way...
What am I doing wrong?
Code to save data:
SQLiteConnection cnn = new SQLiteConnection("Data Source=C:\temp\database.s3db");
cnn.Open();
SQLiteCommand mycommand = new SQLiteCommand(cnn);
mycommand.CommandText = "INSERT INTO images (image_name, tags, relevance) VALUES (\"Example Image åäö.jpg\", \"test\", 3)";
mycommand.ExecuteNonQuery();
cnn.Close();
cnn.Dispose();
Upvotes: 1
Views: 2629
Reputation: 1013
Try this:
private IDbDataParameter AddParameter(IDbCommand command, string paramName, DbType type, object value)
{
IDbDataParameter parameter = command.CreateParameter();
parameter.ParameterName = paramName;
parameter.DbType = type;
if (value != null)
parameter.Value = value;
else
parameter.Value = DBNull.Value;
command.Parameters.Add(parameter);
return parameter;
}
mycommand.CommandText = "INSERT INTO images (image_name, tags, relevance) VALUES (@image_name, @tags, @relevance)";
AddParameter(mycommand, "@image_name", DbType.String, "Example Image åäö.jpg");
AddParameter(mycommand, "@tags", DbType.String, "Test");
AddParameter(mycommand, "@relevance", DbType.Int32, 3);
mycommand.ExecuteNonQuery();
Don't use the DbType.AnsiString or you will have the same problems as you're having now.
Upvotes: 1