Docker下的mysql设置字符集

2018-03-12 agleamad

Mysql的官方镜像mysql:8,可用以下命令启动容器:

docker run --name mysql002 -p 3306:3306 -e MYSQL_ROOT_PASSWORD=888888 -idt mysql:8

如果用Springboot的JPA starter访问此数据库,由于数据库没有设置字符集,springboot应用会抛出以下异常:

java.sql.SQLException: Unknown initial character set index '255' received from server. Initial client character set can be forced via the 'characterEncoding' property.
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1073)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:987)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:982)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:927)
    at com.mysql.jdbc.ConnectionImpl.configureClientCharacterSet(ConnectionImpl.java:1794)
    at 
    ......
    ...
    .

关键信息是这一行:Unknown initial character set index ‘255’ received from server;

由于没有设置字符集导致获取server charset失败,可以使用以下启动命令来创建容器并设置字符集参数:

docker run --name mysql005 -p 3306:3306 -e MYSQL_ROOT_PASSWORD=888888 -idt mysql:8 --character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci

和之前创建容器的命令相比,多了两个参数–character-set-server=utf8mb4 –collation-server=utf8mb4_unicode_ci,这样mysql容器就设置好字符集了,再次启动springboot应用操作数据库,一切正常;