mysql - 将有效的 4 字节 UTF-8 序列插入 MySQL 时出错

标签 mysql go unicode utf-8

我有以下 UTF-8 字节字符串,我试图将其存储在 MySQL 表 (utf8mb4) 中,但 mysql 服务器出现故障。

...
db.Exec("SET NAMES 'utf8mb4'; SET CHARACTER SET utf8mb4;")

var badBytes = []byte{
    34, 48, 34, 32, 47, 62, 66, 117, 121, 32, 105, 116, 32, 110, 111, 119, 32,
    240, 159, 147, 149, 32, 60, 97, 32, 104, 114, 101, 102, 61, 34, 104, 116,
}

fmt.Println("UTF8 Valid", utf8.Valid(badBytes))
fmt.Println()
fmt.Println(string(badBytes))
fmt.Println()

res, err := db.Exec("INSERT INTO demo (body) VALUES (?)", string(badBytes))
if err != nil {
    log.Fatal(err)
}

id, err := res.LastInsertId()
fmt.Println(id, err)

输出如下

UTF8 Valid true

="1" border="0" />Buy it now 📕 <a href="ht_tl

Error 1366: Incorrect string value: '\xF0\x9F\x93\x95 <...' for column 'body' at row 1

MySQL表和连接都是utf8mb4:

CREATE TABLE `demo` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `body` text COLLATE utf8mb4_unicode_ci,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

最佳答案

Like @Rico said我需要指定排序规则 (utf8mb4_unicode_ci),因此 go-mysql 库不会默认为 utf8 并导致我的 4 字节 unicode rune 出现问题(mysql 的 utf8 最多只支持 3 字节 unicode)。

[username[:password]@][protocol[(address)]]/dbname?collation=utf8mb4_unicode_ci

参见 go-sql-driver readme获取更多信息。

关于mysql - 将有效的 4 字节 UTF-8 序列插入 MySQL 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41288165/

相关文章:

mysql - 如何构建具有多个条件的复杂 MySQL 查询

go - 在 Golang 中验证语言环境字符串

java - 在 NetBeans 中看不到 Sinhala Unicode 字符

unicode - Karate - 如何处理 unicode 字符?

java - 如何使用 java/scala 将图像数据插入 mySql mediumtext 字段?

MySQL CTE - 是否可以迭代数字范围?

mysql - 错误 2003 (HY000) : Can't connect to MySQL server on '127.0.0.1:3306' (111)

unit-testing - 如何测试 ioutil.ReadFile 和 os.Stat?

go - 如何从 mux in go 获取可用路由?

ruby - 为什么我的 JSON 提要中的这个 Unicode/UTF-8 "En Dash"字符在我下载时会被损坏?