Avoid garbled characters when accessing Chinese Characters in C # and MySQL,
When socket is used for network program development, Chinese characters are sent and received in most cases. If the sent string is processed by default, A bunch of garbled characters are usually obtained.
Because Chinese characters are expressed in double bytes, the processing of strings containing Chinese characters must be in UNICODE encoding mode. That is to say, when sending a Chinese string using a socket, the string must be converted to the UNICODE format in advance.
The following is a simple socket communication code.
// Server code
Try {IPAddress MyIP = IPAddress. parse ("127.0.0.1"); TcpListener MyListener = new TcpListener (MyIP, Convert. toInt16 ("1235"); MyListener. start (); Socket MySocket = MyListener. acceptSocket (); byte [] MyData = new byte [256]; MySocket. receive (MyData); this. richTextBox1.AppendText (System. text. encoding. unicode. getString (MyData); UnicodeEncoding MyInfo = new UnicodeEncoding (); MySocket. send (MyInfo. getByte S ("From Server: Hello! I am a server ");} catch (Exception ex) {MessageBox. Show (ex. Message," Message prompt ", MessageBoxButtons. OK, MessageBoxIcon. Information );}
// Client code
Try {TcpClient MyClient = new TcpClient (); MyClient. connect ("127.0.0.1", Convert. toInt16 ("1235"); Stream MyStream = MyClient. getStream (); UnicodeEncoding MyInfo = new UnicodeEncoding (); byte [] MyData = new byte [256]; byte [] MySendByte = MyInfo. getBytes ("From Client: Hello! I am a client "); MyStream. write (MySendByte, 0, MySendByte. length); MyStream. read (MyData, 0,256); this. richTextBox1.AppendText (System. text. encoding. unicode. getString (MyData);} catch (Exception ex) {MessageBox. show (ex. message, "Message prompt", MessageBoxButtons. OK, MessageBoxIcon. information );}
In addition, Chinese access to the database is also a headache. In fact, it is very easy to solve this problem. The following is a piece of SQL Server code:
Try {SqlConnection MyConnect = new SqlConnection (m_ConnectionStrings); // Insert a new record string MySQL = string. format ("insert into [BSM_SystemServiceInfoTable] VALUES ({0}, n' {1} ', n' {2}', n' {3 }', n' {4} ') ", AgentID, data [1], data [2], data [3], data [0]); MyCommand = new SqlCommand (MySQL, myConnect); MyCommand. connection. open (); MyCommand. executeNonQuery (); MyCommand. connection. close ();} catch (System. exception e) {MessageBox. show (e. toString ());}
We can see that in the SQL script command, all the string parameters have an additional character "N", which is declared to be encoded in UNICODE mode. Of course, note that, if the field value may contain Chinese characters, the field type must be declared as nchar, nvarchar, and ntext. Here, n indicates the same meaning.