Unicode strings into a SQLite database

强颜欢笑 提交于 2019-12-01 06:33:38

问题


I would like some help with my Visual Studio C# code with inserting unicode strings into a SQLite database.

Below is my test code to write a test string to the database:

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

When I view the database/table (using SQLite Administrator) the string looks like this: á à ñ ç é á

As a test, I can copy & paste the string direct into the database using SQLite Administrator and the string is saved and can subsequently be viewed OK.

I have tried toggling "UseUTF16Encoding=True;" True / False - no difference.

Any ideas what I'm doing wrong.


回答1:


This problem turned out to be an issue with the SQLite Administrator app I was using to view/check the db/data. Seems it was this app that would not display the characters correctly when inserted by my code. Strangely though if you used the SQLite Administrator app to add the test text directly (by copy & pasting the test string into the table/field) it would display, save & subsequently view OK. Anyway now using SourceForge SQLite Database Browser to check my code writes correctly and all seems in order.

Many thanks for anyone who took the time to comment, hope this is of help to someone else.




回答2:


You can try with this code

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


来源:https://stackoverflow.com/questions/12357754/unicode-strings-into-a-sqlite-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!