在昨天写东西的时候,要向mysq中插入一条数据,在我插入数据时,我有在数据中的一个字段添加了中文。导致中文插不进去,今天捣鼓了一段时间,成功将中文添加到了数据库,我猜想原因有二:
- 我的sql语句写错了,在拼接sql语句的时候,我没有给要插入的中文添上单引号,
$catname为从客户端提交上来的一个值为中文的不带引号的变量
错误代码:
$sql = "insert into cat(catname) values($catname)";
$sql = "insert into cat(catname) values(".$catname.")";
正确代码:
$sql = "insert into cat(catname) values('".$catname."')";
2.数据库的默认字符集错了,
没有将数据库的默认字符集改成utf-8格式,因为mysql的默认字符集为latin1,而不是utf-8,gbk等支持中文的字符集。解决方法:
修改数据库的配置文件,将数据库的安装目录下的my-default.ini文件复制出来,改格式为my.ini,并且添加[mysql]# 设置mysql客户端默认字符集default-character-set=utf8 # 服务端使用的字符集默认为8比特编码的latin1字符集character-set-server=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.
[mysql]
# 设置mysql客户端默认字符集
default-character-set=utf8 //设置数据库默认编码
[mysqld]
# 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 = E:\environment\mysql\mysql56
datadir = E:\environment\mysql\mysql56\data
# port = .....
# server_id = .....
# 服务端使用的字符集默认为8比特编码的latin1字符集
character-set-server=utf8 //设置服务器编码,
# 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
至此,在解决完以上两个内容后,成功的将带中文的sql语句插入了数据库。
总结:
1.数据无法导入,首先检查自己写的sql语句是否正确,
2.查看数据库的编码格式,本次使用的相关的语句为:
show variables like 'character%';
show variables like 'collation%'; //collation:校对;斋日的点心;牧师职务
3.在使用sql语句的时候,发现插入的字符串为数字的时候不需要加引号,中文的时候必须要加引号,此问题还有待研究。
首次编辑时间 2018.6.20
网友评论