C#中字符編碼:sql語句中包含中文字符轉換爲utf8編碼

這個問題困擾了我好長時間,終於解決了。postgreSQL數據庫使用的是utf8編碼,如果執行的sql語句中包含中文字符需要字符轉換,但是一直轉換失敗。

如下代碼實現utf8的轉換

            string sql = string.Format("update test_temp set name = '{0}' where id = {1}", "測試數據", "1");
	    Encoding utf8= Encoding.UTF8;
            Encoding defaultCode= Encoding.Default;
            byte[] defaultBytes = utf8.GetBytes(sql);
            byte[] utf8Bytes = Encoding.Convert(defaultCode, utf8, defaultBytes);
            char[] utf8Chars = new char[utf8.GetCharCount(utf8Bytes, 0, utf8Bytes.Length)];
            utf8.GetChars(utf8Bytes, 0, utf8Bytes.Length, utf8Chars, 0);
            string utf8String = new string(utf8Chars);



實現參考自如下代碼

static void Main()
      {
         string utf8String = "騫垮憡涓戦椈";

         // Create two different encodings.
         Encoding utf8= Encoding.UTF8;
         Encoding defaultCode= Encoding.Default;

         // Convert the string into a byte[].
         byte[] utf8Bytes = default.GetBytes(utf8String );

         // Perform the conversion from one encoding to the other.
         byte[] defaultBytes = Encoding.Convert(utf8, defaultCode, utf8Bytes );
            
         // Convert the new byte[] into a char[] and then into a string.
         // This is a slightly different approach to converting to illustrate
         // the use of GetCharCount/GetChars.
         char[] defaultChars = new char[defaultCode.GetCharCount(defaultBytes , 0, defaultBytes .Length)];
         defaultCode.GetChars(defaultBytes , 0, defaultBytes .Length, defaultChars , 0);
         string defaultString = new string(defaultChars );

         // Display the strings created before and after the conversion.
         Console.WriteLine("Original string: {0}", utf8String);
         Console.WriteLine("Ascii converted string: {0}", defaultString);

//或者如下:
         byte[] buffer1 = Encoding.Default.GetBytes(utf8String );
         byte[] buffer2 = Encoding.Convert(Encoding.UTF8, Encoding.Default, buffer1, 0, buffer1.Length);
         string strBuffer = Encoding.Default.GetString(buffer2, 0, buffer2.Length);
      }


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章