使用Navicat Mysql 工具采用默认编码连接进入后
show variable like '%char%'; 结果如下:
表中有一字段存储中文,设置字符集如下:
现在我在Eclipse中使用jdbc 连接查询这个字段 (IDE 采用UTF8 存储)
URL:jdbc:mysql://xxxxx.db.com:3306/database
代码如下:
package test; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Statement; public class TestDB { private static Connection connection; static{ try{ Class.forName("com.mysql.jdbc.Driver") ; //?useUnicode=true&characterEncoding=utf8 connection = DriverManager.getConnection("jdbc:mysql://xxxx.db.com:3306/database", "xxxxx", "xxxxxx6"); }catch(Exception ex){ ex.printStackTrace(); } } public static void main(String[] args)throws Exception { // connection.createStatement().execute("set names latin1"); /*connection.createStatement().execute("SET character_set_results=latin1;"); connection.createStatement().execute("set character_set_connection=latin1;"); connection.createStatement().execute("set character_set_client=latin1;"); */ Statement stm = connection.createStatement(); ResultSet rs1 = stm.executeQuery("show VARIABLES like '%char%'"); while(rs1.next()){ System.out.println(rs1.getString("Variable_name")+"\t"+rs1.getString("Value")); } //PreparedStatement pstmt = connection.prepareStatement("select nick from t_login where uid = 9714") ; //select owner as info from t_info_5 where uid = 5859 PreparedStatement pstmt = connection.prepareStatement("select owner as nick from xxxx_table where uid = 225 ") ; ResultSet rs = pstmt.executeQuery(); while(rs.next()){ String val = rs.getString("nick"); System.out.println(val); System.out.println("========================"); String val1 = new String(val.getBytes("latin1"),"utf8"); System.out.println(val1); String val2 = new String(val.getBytes("latin1"),"gbk"); System.out.println(val2); String val3 = new String(val.getBytes("utf8"),"gbk"); System.out.println(val3); String val4 = new String(val.getBytes("utf8"),"latin1"); System.out.println(val4); String val5 = new String(val.getBytes("gbk"),"latin1"); System.out.println(val5); String val6 = new String(val.getBytes("gbk"),"utf8"); System.out.println(val6); } connection.close(); } }
结果如下:
求解,在不改变DB编码的情况下正确显示出中文来,谢谢!
你数据存储是什么编码格式解码时就用什么格式的。手机不好看你代码,有时间一起研究下
数据库里面乱码了吗?
在nativat mysql中 直接查询是乱码,但如果执行了 set names latin1后再查询就会正确显示中文.
@阳光天下: 你可以把这句加到 select前面先执行一下
@Mr_Lxs: 用jdbc怎么写呢?
@阳光天下: 就是把 set names 'latin1'; 加到你执行的sql语句前面一块执行啊。
@Mr_Lxs: 这样不能执行的.谢谢
@阳光天下: 为什么不能执行?
@阳光天下: 我用php测试的 先执行set names 'latin1'; 在执行查询这时的编码就改变过来了
@Mr_Lxs: php 我在网上看过,我用nodejs也试过 conn.query("set names latin1"); 这样的代码,是可以正常查出的,但是java jdbc就是不行.
mysql driver 中SingleByteCharsetConverter 强制转码了并且采用的是cp1252,所以显示时由cp1252转成utf8就OK了