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

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

WBOY
Release: 2016-06-01 13:00:42
Original
942 people have browsed it

当用到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);
}

Copy after login

//客户端代码

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);
}
Copy after login

此外,数据库中中文的存取也是一件令人头疼的事,其实要解决这个问题很简单,下面是一段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 ());
}

Copy after login

 

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

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template