Home  >  Article  >  Backend Development  >  MySQL encoding issue when inserting using Go driver

MySQL encoding issue when inserting using Go driver

WBOY
WBOYforward
2024-02-09 16:00:10552browse

MySQL encoding issue when inserting using Go driver

php Xiaobian Yuzai brings you a solution to the MySQL coding problem when using the Go driver to insert. When using Go to write MySQL insertion operations, you sometimes encounter coding inconsistencies, resulting in garbled data insertion or failure to be inserted. This article will introduce you in detail how to solve this problem and make your data insertion operation smoother.

Question content

I am trying to store utf-8 text into a table encoded as latin1_swedish_ci. I can't change the encoding because I don't have direct access to the database. So I'm trying to encode text to latin-1 using this go library that provides an encoder, and this library has functions that wrap the encoder so that it replaces invalid characters instead of returning an error.

But when I try to insert the row, mysql complains error 1366: Row 1 Incorrect string value for column "description": "\\xe7\\xe3o pa...".

I tried writing the same text to a file and file -i reported this 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 I know very little about coding.

Thanks in advance.

Solution

Are you expecting çã?

The problem is easily solved. When inserting text, mysql will happily convert from latin1 to utf8. But you have to tell it that your client is using latin1. This may be done during connection to mysql, which currently may default to utf8 or utf-8 or utf8mb4. A bit like

charset=latin1

The above is the detailed content of MySQL encoding issue when inserting using Go driver. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete