在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
本文实例分析了mysql存储emoji表情报错的处理方法。分享给大家供大家参考,具体如下: utf-8编码可能2个字节、3个字节、4个字节的字符,但是MySQL的utf8编码只支持3字节的数据,而移动端的表情数据是4个字节的字符。如果直接往采用utf-8编码的数据库中插入表情数据,Java程序中将报SQL异常:
可以对4字节的字符进行编码存储,然后取出来的时候,再进行解码。但是这样做会使得任何使用该字符的地方都要进行编码与解码。 utf8mb4编码是utf8编码的超集,兼容utf8,并且能存储4字节的表情字符。 更改数据库的编码为utf8mb4: 1. MySQL的版本 utf8mb4的最低mysql版本支持版本为5.5.3+,若不是,请升级到较新版本。 2. MySQL驱动 5.1.34可用,最低不能低于5.1.13 3.修改MySQL配置文件 修改mysql配置文件my.cnf(windows为my.ini) my.cnf一般在etc/mysql/my.cnf位置。找到后请在以下三部分里添加如下内容: [client] default-character-set = utf8mb4 [mysql] default-character-set = utf8mb4 [mysqld] character-set-client-handshake = FALSE character-set-server = utf8mb4 collation-server = utf8mb4_unicode_ci init_connect='SET NAMES utf8mb4' 4. 重启数据库,检查变量 复制代码 代码如下: SHOW VARIABLES WHERE Variable_name LIKE 'character_set_%' OR Variable_name LIKE 'collation%';
collation_connection 、collation_database 、collation_server是什么没关系。 但必须保证
这几个变量必须是utf8mb4。 5. 数据库连接的配置 数据库连接参数中:
而 6. 将数据库和已经建好的表也转换成utf8mb4 更改数据库编码: 复制代码 代码如下: ALTER DATABASE caitu99 CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;
更改表编码: 复制代码 代码如下: ALTER TABLE TABLE_NAME CONVERT TO CHARACTER SET utf8mb4 COLLATEutf8mb4_general_ci;
如有必要,还可以更改列的编码 7、在第3步设置character_set_database,character_set_server不成功的可以试下直接在mysql.exe下 set @@character_set_server='utf8mb4'; set @@character_set_database='utf8mb4'; 这下数据库就可以存下emoji表情的编码了。 附上我的my.ini # 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. [client] default-character-set = utf8mb4 [mysql] default-character-set = utf8mb4 [mysqld] character-set-client-handshake = FALSE character-set-server = utf8mb4 collation-server = utf8mb4_unicode_ci init_connect='SET NAMES utf8mb4' # 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 更多关于MySQL相关内容感兴趣的读者可查看本站专题:《MySQL存储过程技巧大全》、《MySQL常用函数大汇总》、《MySQL日志操作技巧大全》、《MySQL事务操作技巧汇总》及《MySQL数据库锁相关技巧汇总》 希望本文所述对大家MySQL数据库计有所帮助。 |
请发表评论