duanpo7354 2016-11-04 17:44
浏览 402
已采纳

Golang MySQL 1366不正确的字符串值错误

I am inserting strings into my database but getting the MySQL 1366 error for invalid string byte sequences.

2016/11/04 13:33:40 Error 1366: Incorrect string value: '\x89PNG\x0D\x0A...' for column 'text' at row 1
2016/11/04 13:33:56 Error 1366: Incorrect string value: '\xB6\xEB\xE4\x0B\x92\xEE...' for column 'text' at row 1
2016/11/04 13:33:56 Error 1366: Incorrect string value: '\xFF\xD8\xFF\xE0\x00\x10...' for column 'text' at row 1
2016/11/04 13:34:35 Error 1366: Incorrect string value: '\x9C]\x91\xD1k\xC2...' for column 'text' at row 1

My MySQL config is set for utf8mb4 as shown below:

mysql> SHOW VARIABLES LIKE 'character_set%';
+--------------------------+----------------------------+
| Variable_name            | Value                      |
+--------------------------+----------------------------+
| character_set_client     | utf8mb4                    |
| character_set_connection | utf8mb4                    |
| character_set_database   | utf8mb4                    |
| character_set_filesystem | binary                     |
| character_set_results    | utf8mb4                    |
| character_set_server     | utf8mb4                    |
| character_set_system     | utf8                       |
| character_sets_dir       | /usr/share/mysql/charsets/ |
+--------------------------+----------------------------+
8 rows in set (0.00 sec)

My database connection pool looks like this:

db, err = sql.Open("mysql", config.User+":"+config.Password+"@tcp("+config.Host+")/"+config.Database)
if err != nil {
    log.Fatal(err)
}

db.Exec("SET NAMES 'utf8mb4'; SET CHARACTER SET utf8mb4;")

What am I still missing?

  • 写回答

2条回答 默认 最新

  • dongmisa4779 2016-11-04 17:49
    关注

    Those are not valid UTF-8 strings; those are binary data (the first is a PNG file!). You'll need to store them in a real binary column, since MySQL does do UTF-8-specific operations like case folding and language collation. (Go does not enforce UTF-8 encoding on strings, so Go doesn't complain. Go only uses UTF-8 to encode string literals, but the \x escape sequence overrides this. And of course, range, []rune conversion, and various packages assume strings are UTF-8.)

    You can check if a string is a valid sequence with utf8.ValidString().

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)