简体   繁体   English

用Go驱动插入时出现MySQL编码问题

[英]MySQL encoding problem when inserting with Go driver

I'm trying to store utf-8 text into a table which encoding is latin1_swedish_ci.我正在尝试将 utf-8 文本存储到编码为 latin1_swedish_ci 的表中。 I can't change the encoding since I do not have direct access to the the db.我无法更改编码,因为我无法直接访问数据库。 So what I'm trying is encode the text into latin-1 with this Go library that provides the encoder and this one that has a function that wraps the encoder so it replaces the invalid characters instead of returning an error.所以我正在尝试的是使用这个提供编码器的 Go 库将文本编码为 latin-1,这个库有一个 function 来包装编码器,这样它就可以替换无效字符而不是返回错误。

But when I try to insert the row mysql complains Error 1366: Incorrect string value: '\\xE7\\xE3o pa...' for column 'description' at row 1 .但是,当我尝试插入行 mysql 时,会抱怨Error 1366: Incorrect string value: '\\xE7\\xE3o pa...' for column 'description' at row 1

I tried writing the same text to a file and file -I reports this file.txt: application/octet-stream; charset=binary我尝试将相同的文本写入文件和file -I报告此file.txt: application/octet-stream; charset=binary file.txt: application/octet-stream; charset=binary . file.txt: application/octet-stream; charset=binary

Example例子

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))
}
    

I'm probably missing something very obvious but my knowledge about encodings is very poor.我可能遗漏了一些非常明显的东西,但我对编码的了解很差。

Thanks in advace.在此先感谢。

Were you expecting çã ?你期待çã吗?

The problem is easily solved.问题很容易解决。 MySQL will gladly translate from latin1 to utf8 while INSERTing text. INSERTing很乐意在插入文本时将 latin1 翻译成 utf8。 But you must tell it that your client is using latin1.但是你必须告诉它你的客户正在使用 latin1。 That is probably done during the connection to MySQL, and is probably defaulted to utf8 or UTF-8 or utf8mb4 currently.这可能是在连接到 MySQL 期间完成的,目前可能默认为 utf8 或 UTF-8 或 utf8mb4。 It is something like有点像

charset=latin1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM