php小编鱼仔给大家带来关于使用Go驱动插入时MySQL编码问题的解决方法。在使用Go编写MySQL插入操作时,有时会遇到编码不一致的问题,导致数据插入出现乱码或无法插入的情况。这篇文章将为大家详细介绍如何解决这个问题,让你的数据插入操作更加顺畅。
我正在尝试将 utf-8 文本存储到编码为 latin1_swedish_ci 的表中。我无法更改编码,因为我无法直接访问数据库。所以我正在尝试使用这个提供编码器的 go 库将文本编码为 latin-1,并且这个库具有包装编码器的函数,以便它替换无效字符而不是返回错误。
但是当我尝试插入行时,mysql 抱怨 error 1366:第 1 行
列“description”的字符串值不正确:“\xe7\xe3o pa...”。
我尝试将相同的文本写入文件,并且 file -i
报告此 file.txt: application/octet-stream;字符集=binary
。
示例
package main import ( "fmt" "os" "golang.org/x/text/encoding" "golang.org/x/text/encoding/charmap" ) func main() { s := "foo – bar" encoder := charmap.ISO8859_1.NewEncoder() encoder = encoding.ReplaceUnsupported(encoder) encoded, err := encoder.String(s) if err != nil { panic(err) } fmt.Println(s) fmt.Println(encoded) fmt.Printf("%q\n", encoded) /* file test */ f, err := os.Create("file.txt") if err != nil { panic(err) } defer f.Close() w := encoder.Writer(f) w.Write([]byte(s)) }
我可能错过了一些非常明显的东西,但我对编码的了解非常少。
提前致谢。
您在期待 çã
吗?
问题很容易解决。当 inserting
文本时,mysql 会很乐意从 latin1 转换为 utf8。但你必须告诉它你的客户端正在使用 latin1。这可能是在连接 mysql 期间完成的,目前可能默认为 utf8 或 utf-8 或 utf8mb4。有点像
charset=latin1
以上是使用Go驱动插入时MySQL编码问题的详细内容。更多信息请关注PHP中文网其他相关文章!