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

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

mysql> show create table testapp_article;
+-----------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table | Create Table |
+-----------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| testapp_article | CREATE TABLE `testapp_article` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(100) NOT NULL,
`content` longtext,
`author` varchar(20) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 |
+-----------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

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;
Query OK, 0 rows affected (0.18 sec)
Records: 0 Duplicates: 0 Warnings: 0

mysql> show create table testapp_article;
+-----------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table | Create Table |
+-----------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| testapp_article | CREATE TABLE `testapp_article` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(100) NOT NULL,
`content` longtext,
`author` varchar(20) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 


此后再往此 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 了。

 

参照:https://blog.csdn.net/paullinjie/article/details/80312863 

posted @ 2019-01-07 17:36  lijavasy  阅读(3381)  评论(0编辑  收藏  举报