我有以下 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/