mysql 插入中文字段报错 "Incorrect string value: '\\xE6\\xB5\\x8B\\xE8\\xAF\\x95...' for column 'title' at ro

MySQL中默认字符集的设置有四级:服务器级,数据库级,表级,字段级 ,最终是字段级的字符集设置。
注意前三种均为默认设置,并不代表你的字段最终会使用这个字符集设置。
所以我们建议要用show create table table ; 或show full fields from tableName; 来检查当前表中字段的字符集设置。

  1. 查看database或一个table的编码
    show create database mytestdb;
    show create table testapp_article;

  2. 创建table的时候就使用 utf8 编码
    在每次创建表的时候都在最后加上 character set = utf8 即可:
    如:
    create table test_table (
    id int auto_increment,
    title text,
    content text,
    posted_on datetime,
    primary key (id)
    ) character set = utf8;

  3. 修改已有table的编码
    使用默认编码创建的table是不能支持中文的,这时候使用如下语句对表testapp_article进行修改:
    mysql> alter table testapp_article convert to character set utf8;
    mysql> show create table testapp_article;
    此后再往此 table 插入中文时,就可以正常存储和读取了,但之前插入的中文的乱码还是不能纠正,只是对新插入的数据没有问题。

  4. 修改mysql的配置文件,让 mysql 默认编码为utf8
    在/etc/mysql/mysql.conf.d/mysqld.cnf里面的[mysqld]下面添加如下行:
    [mysqld]
    character-set-server=utf8

  5. 重启服务:
    sudo /etc/init.d/mysql restart
    如果没有错,再创建数据库或者表的时候默认编码应该就是 utf8 了。

猜你喜欢

转载自blog.csdn.net/w13716207404/article/details/102979744