[MySQL] SQL語句中文別名亂碼問題

來源:互聯網
上載者:User

MySQL 驅動: http://www.mysql.com/products/connector/, 根據自己的使用選擇下載

我使用的是ASP.NET, 將下載的驅動解壓, 建一個空白WEB項目, 然後引用解壓出來的 MySql.Data.dll, 添加一個 test.aspx 檔案

test.aspx.vb 檔案代碼如下:

  1. Imports System.Data
  2. Imports System.Data.Common
  3. Imports MySql.Data.MySqlClient
  4. Partial Class test
  5.     Inherits System.Web.UI.Page
  6.     Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
  7.         Dim connection As MySqlConnection
  8.         connection = New MySqlConnection("Server=localhost;Database=webanalytics;Uid=root;Pwd=;CharSet=utf8;")
  9.         connection.Open()
  10.         doTest(New MySqlCommand("select AutoId as `2自動編號4` from Site", connection))
  11.         doTest(New MySqlCommand("select `Id` as `desc描述222` from Site;", connection))
  12.         doTest(New MySqlCommand("select `Domain` as `3網域名稱2domain` from Site;", connection))
  13.         doTest(New MySqlCommand("select `Explain` as `desc描述` from Site;", connection))
  14.         connection.Close()
  15.         connection.Dispose()
  16.     End Sub
  17.     Private Sub doTest(ByVal cmd As DbCommand)
  18.         Dim reader As DbDataReader = cmd.ExecuteReader()
  19.         response.Write("<h3>" & reader.GetName(0) & "</h3>")
  20.         While reader.Read
  21.             response.Write("<p>" & reader.GetValue(0))
  22.         End While
  23.         reader.Close()
  24.         cmd.Dispose()
  25.     End Sub
  26. End Class

在瀏覽器中查看結果如下:

注:最後一條資料在資料庫中就是亂碼

經反覆測試, 發現問題出現在 DbDataReader, 如果只使用DbDataReader.GetName()擷取欄位的別名將不會現現亂碼, 當讀取了資料時, 並且最後一次讀取的是非字串類型, 那麼下次(沒有關閉連線物件)再次使用DbDataReader讀取欄位別名時會出現亂碼(當然別名得是中文).

這樣有以下方案可以解決.
1. 每次使用完 DbDataReader 後關閉串連, 再重新開啟;
2. DbDataReader讀取完資料之後, 再讀一個字串的欄位;

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.