首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫

C# 與 MySQL 中文亂碼解決方案:Unicode 編碼統一實踐

     編輯:MySQL 資料庫相關知識

Socket 通訊中文處理

關鍵點:發送端與接收端統一使用 Unicode 編碼。

伺服端代碼

try {
    IPAddress MyIP = IPAddress.Parse("127.0.0.1");
    TcpListener MyListener = new TcpListener(MyIP, 1235);
    MyListener.Start();
    Socket MySocket = MyListener.AcceptSocket();
    byte[] MyData = new byte[256];
    MySocket.Receive(MyData);
    // 接收時用 Unicode 解碼
    this.richTextBox1.AppendText(System.Text.Encoding.Unicode.GetString(MyData));

    // 發送時用 Unicode 編碼
    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", 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 中文存取

關鍵點:參數前綴 N + 欄位型別用 N 系列。

-- 建表時
CREATE TABLE T (
  col1 NVARCHAR(100),  -- N 系列支援 Unicode
  col2 NTEXT
);

-- 參數化查詢(推薦)
INSERT INTO T VALUES (N'中文內容', N'更多中文');

-- 字串拼接時(不推薦,防注入)
string sql = "INSERT INTO T VALUES (N'" + value1 + "', N'" + value2 + "')";

MySQL 環境下的對應做法

核心原則

  1. 全鏈路統一:資料庫、表、欄位、連線、應用層字串皆為 Unicode
  2. 拒絕拼接:永遠使用參數化查詢,同時解決亂碼與注入
  3. 驅動版本:MySQL Connector/NET 8.0+ 完整支援 utf8mb4
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved
層面SQL ServerMySQL
字元集UTF-16 (NVARCHAR)utf8mb4 (CHARSET=utf8mb4)
連線設定自動協商SET NAMES utf8mb4 或連接字串 CharSet=utf8mb4
參數化SqlParameterMySqlParameter
C# 字串原生 Unicode原生 Unicode,驅動自動轉換