問題:
向mysql 數據庫插入數據是,出現中文亂碼(中文均顯示為‘??’)
原因:
mysql 默認的字符集是latin1,所以我么需要改為ut8編碼才可以
解決:
1、以管理員權限運行cmd窗口
2、查看當前字符集
>net start mysql
啟動mysql服務
>mysql
進入mysql運行環境
>show variables like 'character%';
查看當前字符集編碼情況
其中,character_set_client為客戶端編碼方式;
character_set_connection為建立連接使用的編碼;
character_set_database數據庫的編碼;
character_set_results結果集的編碼;
character_set_server數據庫服務器的編碼;
只要保證以上四個采用的編碼方式一樣,就不會出現亂碼問題。
3、修改數據庫編碼格式
>select @@basedir;
在mysql環境中查看mysql的安裝位置
找到這個安裝位置,下圖為安裝位置下的文件
本機的mysql是通過解壓安裝的,開始時只有my-default.ini文件,無my.ini文件
這時復制一份my-default.init並重命名為my.ini
打開my.ini文件
在[mysqld] 下添加character-set-server=utf8
在[client] 下添加:default-character-set=utf8

# For advice on how to change settings please see
# http://dev.mysql.com/doc/refman/5.6/en/server-configuration-defaults.html
# *** DO NOT EDIT THIS FILE. It's a template which will be copied to the
# *** default location during install, and will be replaced if you
# *** upgrade to a newer version of MySQL.
[mysqld]
character-set-server=utf8
# Remove leading # and set to the amount of RAM for the most important data
# cache in MySQL. Start at 70% of total RAM for dedicated server, else 10%.
# innodb_buffer_pool_size = 128M
# Remove leading # to turn on a very important data integrity option: logging
# changes to the binary log between backups.
# log_bin
# These are commonly set, remove the # and set as required.
# basedir = .....
# datadir = .....
# port = .....
# server_id = .....
# Remove leading # to set options mainly useful for reporting servers.
# The server defaults are faster for transactions and fast SELECTs.
# Adjust sizes as needed, experiment to find the optimal values.
# join_buffer_size = 128M
# sort_buffer_size = 2M
# read_rnd_buffer_size = 2M
sql_mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES
[client]
port=3306
default-character-set=utf8
保存文件
4、重新在mysql環境中查看字符編碼
發現這時的字符編碼已經改為utf8
5、如果更改字符編碼之前已經有創建的數據表,可以通過如下語句,更改已經創建數據表的字符格式
mysql> alter table testapp_article convert to character set utf8;
也可以在創建數據表的時候指定使用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;
參考: