Gorm: How to set utf-8 as default charset?

Created on 7 Apr 2018  路  7Comments  路  Source: go-gorm/gorm

Thanks for this very good lib.
When call:

    db.AutoMigrate(&Product{})

this generate a default latin charset table, no problem for English strings, but when using charaters such as Chinese, error appears:

(Error 1366: Incorrect string value: '\xE9\xA6\x99\xE8\x95\x89' for column 'name' at row 1) 

We can change charset in mysql console, but this is really in-convinient. How to set utf-8 as default charset anyway?

Most helpful comment

@EfimovArtem

I use mysql 5.7
this is my example

args := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8&parseTime=True&loc=Local",
        cfg.Username, cfg.Password, cfg.Host, cfg.Port, cfg.Database)
db, err = gorm.Open("mysql", args)
//err ...
db = db.Set("gorm:table_options", "ENGINE=InnoDB CHARSET=utf8 auto_increment=1")

then db.AutoMigrate(&Product{})

All 7 comments

this is my practice

db.Set("gorm:table_options", "charset=utf8")

hope help you

@dongshimou It didn't help me(

@EfimovArtem

I use mysql 5.7
this is my example

args := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8&parseTime=True&loc=Local",
        cfg.Username, cfg.Password, cfg.Host, cfg.Port, cfg.Database)
db, err = gorm.Open("mysql", args)
//err ...
db = db.Set("gorm:table_options", "ENGINE=InnoDB CHARSET=utf8 auto_increment=1")

then db.AutoMigrate(&Product{})

Thanks for help. I finally end up with change MySQL default encoding after installed it. So that later on new db or table the encoding will be utf-8.

[username[:password]@][protocol[(address)]]/dbname[?param1=value1&...&paramN=valueN]
charset=utf8mb4

https://github.com/go-sql-driver/mysql#charset

@jinfagang, is this all fixed?

Thanks for this very good lib.
When call:

  db.AutoMigrate(&Product{})

this generate a default latin charset table, no problem for English strings, but when using charaters such as Chinese, error appears:

(Error 1366: Incorrect string value: '\xE9\xA6\x99\xE8\x95\x89' for column 'name' at row 1) 

We can change charset in mysql console, but this is really in-convinient. How to set utf-8 as default charset anyway?

Isn't it like Emoji chars? I had the same problem while back, and I moved from utf8 to utf8mb4 character set
Maybe this will help
https://hackernoon.com/today-i-learned-storing-emoji-to-mysql-with-golang-204a093454b7

Was this page helpful?
0 / 5 - 0 ratings