1. 查看一個 database 或一個 table 的編碼
show create database mytestdb;
show create table testapp_article;mysql
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)sql
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進行修改:app
mysql> alter table testapp_article convert to character set utf8;
Query OK, 0 rows affected (0.18 sec)
Records: 0 Duplicates: 0 Warnings: 0post
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 插入中文時,就能夠正常存儲和讀取了,但以前插入的中文的亂碼仍是不能糾正,只是對新插入的數據沒有問題。.net
4. 修改mysql的配置文件,讓 mysql 默認編碼爲utf8rest
在/etc/mysql/mysql.conf.d/mysqld.cnf裏面的[mysqld]下面添加以下行:
[mysqld]
character-set-server=utf8server
5 重啓服務:blog
sudo /etc/init.d/mysql restart
若是沒有錯,再建立數據庫或者表的時候默認編碼應該就是 utf8 了。
參照:https://blog.csdn.net/paullinjie/article/details/80312863