C and MySQL C access to Chinese characters to avoid messy code

  • 2020-10-07 18:54:22
  • OfStack

When socket is used for network program development, Chinese characters will be sent and received in most cases. At this time, if the sent string is processed in the default way, 1 will generally get a heap of scrambled code.

Since Chinese characters are represented by double bytes, the processing of strings containing Chinese characters must be processed according to UNICODE encoding mode, that is, when sending Chinese character strings using socket, the strings must be converted to UNICODE format in advance.

Here is the code for a simple socket communication.

// Server-side 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.GetBytes( " From Server: hello ! I'm the server." ));
}
catch (Exception ex)
{
  MessageBox.Show(ex.Message, "Information 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'm the 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, "Information Prompt" ,MessageBoxButtons.OK,MessageBoxIcon.Information);
}

In addition, access to the Chinese database is also a headache, in fact, to solve this problem is very simple, SQL Server 1 section of code:


try
{
  SqlConnection MyConnect = new SqlConnection(m_ConnectionStrings);
  // Insert 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 ());
}

As you can see, in the SQL script command, there is an extra character "N" in front of all the string parameters. This character declares the encoding as UNICODE. Of course, it should be noted that if the value of the field may contain Chinese characters, the field types must be declared as nchar, nvarchar, ntext, and n.


Related articles: