【问题标题】:How to insert and retrieve data from sqlite database with correct character set?如何使用正确的字符集从 sqlite 数据库中插入和检索数据?
【发布时间】:2012-01-25 14:44:09
【问题描述】:

我正在用 C# 编写一个使用 sqlite 数据库的程序(通过 ADO,System.Data.SQLite)。

问题是,当我从我的 c# 应用程序中插入包含瑞典语或德语字符(åäöüÅÄÖÜ 等)的字符串时,它们被错误地存储在数据库中。 (看起来像 ö 和 ä 等),但如果我使用 SQLite Administrator 将它们直接插入数据库,它们会被正确保存。

此外,当我尝试使用正确存储的 C# 应用程序检索数据时,它以同样的方式搞砸了......

我做错了什么?

保存数据的代码:

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

【问题讨论】:

  • 你必须做某种编码不会或文化类型的检查/编码..?
  • 感谢 DJ KRAZE,看不下去了
  • 试试这个链接并阅读底部的答案,该人谈论安装 SQLLite stackoverflow.com/questions/498670/…
  • 非常感谢!那解决了! SQLite 管理员搞砸了...
  • 太棒了..很高兴我能伸出援手

标签: c# sqlite


【解决方案1】:

试试这个:

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

不要使用 DbType.AnsiString 否则你会遇到和现在一样的问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-28
    • 2019-06-03
    • 1970-01-01
    • 2016-12-06
    • 2011-12-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多