Heim  >  Artikel  >  Datenbank  >  在C#和MySQL中存取中文字符时避免乱码的方法_MySQL

在C#和MySQL中存取中文字符时避免乱码的方法_MySQL

WBOY
WBOYOriginal
2016-06-01 13:00:42897Durchsuche

当用到socket来进行网络程序开发时,大多数情况下会遇到中文字符的发送与接收,这时若对发送的字符串用默认的方式进行处理,则一般会得到一堆乱码。

由于中文字符采用双字节表示,所以对含有中文的字符串的处理一定要按UNICODE编码方式进行处理,也就是说,使用socket发送中文字串时要事先将字串转成UNICODE格式的。

下面是简单的socket通信的代码。

//服务端代码

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:你好!我是服务器”));
}
catch (Exception ex)
{
  MessageBox.Show(ex.Message,“信息提示”,MessageBoxButtons.OK,MessageBoxIcon.Information);
}

 

//客户端代码

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:你好!我是客户端”);
  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,“信息提示”,MessageBoxButtons.OK,MessageBoxIcon.Information);
}

 

此外,数据库中中文的存取也是一件令人头疼的事,其实要解决这个问题很简单,下面是一段SQL Server的代码:

try
{
  SqlConnection MyConnect = new SqlConnection(m_ConnectionStrings);
  //插入新纪录
  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 ());
}

 

可以看到,SQL脚本命令中,所有的字符串参数前多了一个字符“N”,这个字符即声明用UNICODE方式编码,当然,要注意的就是,若字段的值可能含有中文时,必须将该字段类型声明为nchar、nvarchar、ntext,这里的n表示的意思是一样的。

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn