将Unicode字符串存储到SQLite数据库中

4

我希望你能帮我处理一下使用Visual Studio C#将Unicode字符串插入SQLite数据库的代码问题。

以下是我的测试代码,用于将测试字符串写入数据库:

         string testStr = "á Á ñ ç é á";

         SQLiteConnection mydataConnection = new SQLiteConnection();  // setup new sql connection obj
         try
         {
             ////                    SQLite DB
             mydataConnection.ConnectionString =
             "Data Source=C:\\Users\\John\\Desktop\\location.db; Version=3; UseUTF16Encoding=True;Synchronous=Normal;New=False"; // set up the connection string

             mydataConnection.Open();  // open the connection to the db

             SQLiteCommand myCmd = new SQLiteCommand();   // create a new command object
             myCmd.Connection = mydataConnection;   // whats its connected to, see above connection string


             SQLiteParameterCollection myParameters = myCmd.Parameters; // good pratice to use parameters to pass data to db
             myParameters.AddWithValue("@name", testStr);  //
             myCmd.CommandText = "INSERT INTO location (name) VALUES (@name)";
             myCmd.ExecuteNonQuery();
         }
         catch (SQLiteException d)
         {
             string myerror = "Database Error" + d;
             MessageBox.Show(myerror);
         }
    finally  // good pratice to close db connection in a finally so exceptions dont leave open.
         {
             mydataConnection.Close();
         } 

当我查看数据库/表(使用SQLite管理员)时,字符串看起来像这样:á ñ ç é á

作为测试,我可以直接将该字符串复制并粘贴到使用SQLite管理员的数据库中,该字符串将被保存,并且随后可以正常查看。

我尝试切换“UseUTF16Encoding=True;”True / False-没有任何区别。

您有什么想法我做错了什么。


尝试使用C#插入一行,然后再使用SQLite管理员插入一行。接下来,使用不同的编码方式在C#中读取它们,并查看结果(我猜测SQLite管理员使用的编码方式不是C#默认识别的)。 - Thymine
2个回答

3
这个问题实际上是我使用的SQLite管理员应用程序的问题,用于查看/检查数据库/数据。似乎是这个应用程序无法正确显示由我的代码插入的字符。但奇怪的是,如果您使用SQLite管理员应用程序直接添加测试文本(通过将测试字符串复制并粘贴到表/字段中),它将显示、保存和随后查看OK。现在,我使用SourceForge SQLite数据库浏览器来检查我的代码是否正常编写,并且一切都看起来很正常。
非常感谢所有抽出时间发表评论的人,希望这对其他人有所帮助。

2
您可以尝试使用以下代码:

您可以使用此代码进行尝试

byte[] encod = Encoding.Default.GetBytes(testStr );
string result = Encoding.UTF8.GetString(encod);
myParameters.AddWithValue("@name", result);

非常感谢Aghilas的建议,但是你的建议在数据库中产生了字符串“� � � � � �”。 我之前尝试过类似的解决方案,但都没有成功。 - JohnHk
尝试使用Encoding.Unicode(即UTF16)来解决这个问题? - Thymine
谢谢你的建议,但我已经尝试了以下所有编码来进行实验:Encoding.UTF8、Encoding.Unicode、Encoding.UTF32、Encoding.BigEndianUnicode、Encoding.UTF7和Encoding.ASCII。但是都没有得到期望的结果。 - JohnHk

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接