在很多社交平台,博客上,可以看到有好多表情符号,这些表情符号是由unicode编码定义的,并不是我们以为的图片。在mysql中,如果插入的这些数据,即使数据库字符是utf8编码,也会报错。这是因为utf8编码不能包含这些特殊表情符号,得使用utf8mb4. 以下是解决步骤:
1. 修改数据库配置文件 my.ini/my.conf(linux)
[mysql]
default-character-set=utf8mb4
character-set-server=utf8mb4
collation_server=utf8mb4_unicode_ci
[mysqld]
character-set-server=utf8mb4
init-connect="SET NAMES utf8mb4"
在配置文件中修改后,以后添加的table, 字段一般就是utf8mb4了
2. 修改数据库,数据表,字段的编码
如果之前数据库不是utf8mb4,则需要单独修改table和字段
修改某张表的某个字段
ALTER TABLE mytable MODIFY COLUMN `content` MEDIUMTEXT CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci
修改整个数据库
ALTER DATABASE databasename CHARACTER SET utf8 COLLATE utf8mb4_unicode_ci;
3.在编程代码中使用合适的连接方式
以java jdbc为例,jdbcUrl为
jdbc:mysql://localhost:3306/mydb?useUnicode=yes&characterEncoding=UTF-8
以上三步,最终结果要确保 数据库,数据表,数据列的字符编码为utf8mb4, 校对规则为utf8mb4_unicode_ci。
[client]
#password = your_password
port = 3306
socket = /tmp/mysql.sock
[mysqld]
port = 3306
socket = /tmp/mysql.sock
datadir = /www/server/data
default_storage_engine = InnoDB
performance_schema_max_table_instances = 400
table_definition_cache = 400
skip-external-locking
key_buffer_size = 32M
max_allowed_packet = 100G
table_open_cache = 128
sort_buffer_size = 768K
net_buffer_length = 4K
read_buffer_size = 768K
read_rnd_buffer_size = 256K
myisam_sort_buffer_size = 8M
thread_cache_size = 16
query_cache_size = 16M
tmp_table_size = 32M
sql-mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES
character-set-server=utf8mb4
init-connect="SET NAMES utf8mb4"
explicit_defaults_for_timestamp = true
#skip-name-resolve
max_connections = 500
max_connect_errors = 100
open_files_limit = 65535
log-bin=mysql-bin
binlog_format=mixed
server-id = 1
expire_logs_days = 10
slow_query_log=1
slow-query-log-file=/www/server/data/mysql-slow.log
long_query_time=3
#log_queries_not_using_indexes=on
early-plugin-load = ""
innodb_data_home_dir = /www/server/data
innodb_data_file_path = ibdata1:10M:autoextend
innodb_log_group_home_dir = /www/server/data
innodb_buffer_pool_size = 128M
innodb_log_file_size = 64M
innodb_log_buffer_size = 16M
innodb_flush_log_at_trx_commit = 1
innodb_lock_wait_timeout = 50
innodb_max_dirty_pages_pct = 90
innodb_read_io_threads = 2
innodb_write_io_threads = 2
[mysqldump]
quick
max_allowed_packet = 500M
[mysql]
no-auto-rehash
default-character-set=utf8mb4
character-set-server=utf8mb4
collation_server=utf8mb4_unicode_ci
[myisamchk]
key_buffer_size = 32M
sort_buffer_size = 768K
read_buffer = 2M
write_buffer = 2M
[mysqlhotcopy]
interactive-timeout
本文共 个字数,平均阅读时长 ≈ 分钟,您已阅读:0时0分0秒。
649494848