简体   繁体   English

如何使用正确的字符集从sqlite数据库中插入和检索数据?

[英]How to insert and retrieve data from sqlite database with correct character set?

I am writing a program in C# that's using a sqlite database (throug ADO, System.Data.SQLite). 我正在使用sqlite数据库(通过ADO,System.Data.SQLite)在C#中编写程序。

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. 问题是,当我从c#应用程序中插入包含瑞典语或德语字符(åäöüÅÄÖÖÜ等)的字符串时,它们被错误地存储在数据库中。 (looking like ö and ä ect), but if I insert them directly to the db using SQLite Administrator they are saved correctly. (看起来像¶和Ãect),但是如果我使用SQLite Administrator将它们直接插入到数据库中,它们将被正确保存。

Furthermore, when I try to retrieve data with my C# app that is stored correctly, it's messed up in the same way... 此外,当我尝试使用正确存储的C#应用​​程序检索数据时,它以相同的方式被弄乱了...

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();

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. 不要使用DbType.AnsiString,否则您将遇到与现在相同的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM