You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Go与MySQL中波兰语符号显示异常问题求助

Go语言查询MySQL波兰语字符乱码问题解决

问题现象

使用Go的database/sql模块查询MySQL时,波兰语特殊字符显示乱码(如日志中的wkr�tce dost�pne),但PHP mysqli执行同一查询时显示正常。日志示例:

2022/10/12 13:32:24 Drukarka 3D CR-200B - wkr�tce dost�pne
2022/10/12 13:32:24 Drukarka 3D ED V1 PRO
2022/10/12 13:32:24 Drukarka 3D CR-3040 PRO - wkr�tce dost�pne
2022/10/12 13:32:24 Mikrokontroler BBC micro:bit
2022/10/12 13:32:24 Zestaw Startowy micro:bit
2022/10/12 13:32:24 Niesamowity Samoch�d
2022/10/12 13:32:24 EduBot
2022/10/12 13:32:24 EduDron
2022/10/12 13:32:24 Kreatywny Konstruktor
2022/10/12 13:32:24 Innowacyjny In�ynier
2022/10/12 13:32:24 Matatalab Pro - wkr�tce dost�pne
2022/10/12 13:32:24 Matatalab TaleBot - wkr�tce dost�pne
2022/10/12 13:32:24 Matatalab Lite - wkr�tce dost�pne

相关代码与表结构

Go查询代码

var products []models.Product
var product models.Product

rows, _ := db.Query("select title from products")
defer rows.Close()

for rows.Next() {
    rows.Scan(&product.Title)
    title := utf8string.NewString(product.Title)
    log.Println(fmt.Sprint(title))
    products = append(products, product)
}

json.NewEncoder(w).Encode(products)

MySQL表结构与插入语句

CREATE TABLE `products` (
  `title` mediumtext COLLATE utf8mb4_polish_ci NOT NULL,
  `description` mediumtext COLLATE utf8mb4_polish_ci NOT NULL,
  `content` varchar(1024) COLLATE utf8mb4_polish_ci DEFAULT NULL,
  `isVisible` int(11) DEFAULT NULL,
  `id` bigint(20) UNSIGNED NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_polish_ci;

INSERT INTO `products` (`title`, `description`, `content`, `isVisible`, `id`) VALUES
('Mikrokontroler BBC micro:bit', '<a href=\"https://eduko.pl/robotyka/649-zestaw-startowy-microbit-mikrokontroler-z-czujnikami-i-akcesoriami.html\"><br/><button class=\"btn btn-primary d-none d-lg-flex\">Tutaj znajdziesz zestaw startowy micro:bit</button></a>', 'BBC micro:bit - Wprowadzenie;Scenariusze;:INDEX:;Lekcja 1;Lekcja 2;Lekcja 3;Lekcja 4;Lekcja 5;:INDEX:', 1, 4);

解决方案

  • 指定连接字符集为utf8mb4:在MySQL连接DSN中添加charset=utf8mb4参数,确保连接字符集与数据库一致(MySQL的utf8仅支持3字节字符,utf8mb4支持完整UTF-8)。示例DSN:
    dsn := "user:password@tcp(host:port)/dbname?charset=utf8mb4&parseTime=True&loc=Local"
    db, err := sql.Open("mysql", dsn)
    
  • 移除冗余的utf8string处理:Go原生string已支持UTF-8编码,无需使用utf8string.NewString转换,直接输出字段值即可:
    for rows.Next() {
        err := rows.Scan(&product.Title)
        if err != nil {
            log.Println(err)
            continue
        }
        log.Println(product.Title)
        products = append(products, product)
    }
    
  • 确认模型字段类型:保证models.Product的Title字段为string类型,避免因类型不匹配导致的编码转换错误。

内容的提问来源于stack exchange,提问作者Norbert Wagner

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 14:00:58