这样配置之前在我司的测试环境中 CRUD 是没有问题的,但是后来想在个人的机器上部署一下 MySQL 环境就出问题了,首先为了保证数据的完整性,我将公司测试机的 SQL 全部导出后再导入到个人的 MySQL 环境中,但是诡异的事情发生了:此时在 Java 工程中如果查询的 SQL 中都是英文是可以正常工作的,但如果包含中文(比如 SELECT * FROM USER WHERE name = '张三')是无法查询到结果的。
假设我们要把用编码 A 表示的字符 X,转化为编码 B 的表示形式,而编码 B 的字符集中并没有 X 这个字符,那么此时我们就称这个转换是有损的,如果在 B 的字符集都能找到 A 中的字符,那么就是无损的,所以最简单的方式就是将每个步骤对应的编码字符集都设置成一样的,比如都设置成 UTF-8,这样就肯定没问题了。
开头的问题解答
现在回过头来看一下开头的问题,为什么将 DB 数据从公司的测试机导入到个人机器后,如果 SQL 中包含有中文查询如下 jdbc url 的配置会导致原本正常返回的结果集失效呢?
DB 表数据采用的编码都是 UTF-8,如果只要搞清楚 character_set_client,character_set_connection,character_set_result 这三个编码字符集是啥问题就解决了,这个问题的答案得去官网找,来看下官网是怎么说的
The character encoding between client and server is automatically detected upon connection (provided that the Connector/J connection properties characterEncoding and connectionCollation are not set). You specify the encoding on the server using the system variable character_set_server (for more information, see Server Character Set and Collation). The driver automatically uses the encoding specified by the server.
To override the automatically detected encoding on the client side, use the characterEncoding property in the connection URL to the server. Use Java-style names when specifying character encodings. The following table lists MySQL character set names and their corresponding Java-style names: