使用Java读取Mysql数据的编码问题

使用 java 程序对 Mysql 数据库内数据进行操作,如果使用默认字符集时数据库连接串通常为:  

db.url=jdbc:mysql://192.168.0.137/test?user=root&password=&autoReconnect=true&useUnicode=true

去掉设置:&characterEncoding=utf-8   此时使用的字符集为:ISO-8859-1。因此,插入数据库中的数据会被 Mysql 驱动转换成默认编码:ISO-8859-1。整个数据库中的数据本身不会有什么问题,使用 Mysql 查看的时候看到的是一些问号。但是如果使用 Java 读取这些数据的时候,如果要正确显示,则需要对其进行正确的编码:

使用系统默认的编码方式

插入时:直接给定参数 stringValue ,此时 stringValue 为JVM默认编码
插入后:数据库中 stringValue 值的编码为 ISO-8859-1
读取时:使用 stringValue = new String(stringValue.getBytes(“ISO-8859-1”));进行将编码ISO-8859-1 转换成操作系统的默认编码(GBK)。

上述过程完整描述为

插入时:直接给定参数 stringValue = new String(stringValue.getBytes(), “ISO-8859-1”);
插入后:数据库中 stringValue 值的编码为 ISO-8859-1
读取时:使用 stringValue = new String(stringValue.getBytes(“ISO-8859-1”));进行将编码ISO-8859-1 转换成操作系统的默认编码(GBK)。

采用硬编码形式又可以写成

插入时:直接给定参数 stringValue = new String(stringValue.getBytes(“GBK”), “ISO-8859-1”);
插入后:数据库中 stringValue 值的编码为 ISO-8859-1
读取时:使用 stringValue = new String(stringValue.getBytes(“ISO-8859-1”), “GBK”);进行将编码ISO-8859-1 转换成操作系统的默认编码(GBK)。

3,765 次阅读

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注