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;
+-----------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
+-----------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
`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 |
+-----------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
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
再創建表的時候默認編碼就是 utf8 了。
參照:https://blog.csdn.net/paullinjie/article/details/80312863
mysql 插入中文字段報錯 "Incorrect string value: '\\xE6\\xB5\\x8B\\xE8\\xAF\\x95...' for column 'title' at row 1"