4

SQLite データベースに Unicode 文字列を挿入する Visual Studio C# コードのヘルプが必要です。

以下は、データベースにテスト文字列を書き込むための私のテスト コードです。

         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 Administrator を使用して) データベース/テーブルを表示すると、文字列は次のようになります。

テストとして、SQLite Administrator を使用して文字列をデータベースに直接コピー アンド ペーストすると、文字列が保存され、後で問題なく表示できます。

「UseUTF16Encoding=True;」を切り替えてみました。真/偽 - 違いはありません。

私が間違っていることについてのアイデア。

4

2 に答える 2

3

この問題は、db/data を表示/確認するために使用していた SQLite 管理者アプリの問題であることが判明しました。私のコードで挿入したときに文字が正しく表示されなかったのはこのアプリだったようです。奇妙なことに、SQLite 管理者アプリを使用して (テスト文字列をコピーしてテーブル/フィールドに貼り付けることにより) テスト テキストを直接追加すると、表示、保存、およびその後の表示 OK が表示されます。とにかく、SourceForge SQLite Database Browser を使用して、コードが正しく記述されていることを確認し、すべてが順調に進んでいるようです。

時間を割いてコメントしてくれた人に感謝します。これが他の誰かの助けになることを願っています。

于 2012-09-11T13:55:12.077 に答える
2

このコードで試すことができます

byte[] encod = Encoding.Default.GetBytes(testStr );
string result = Encoding.UTF8.GetString(encod);
myParameters.AddWithValue("@name", result);
于 2012-09-10T19:03:23.613 に答える