java 读取 UTF8字符集的mysql 乱码问题
我要用Java读取一个mysql中的表,表的字符集是用UTF-8的,我试了好几种方法都无法正常查询表中的内容,出来的都有?????,请教高手有什么办法解决。
public static void main(String a[])
{
try
{
Class.forName( "com.mysql.jdbc.Driver ").newInstance();
String url2= "jdbc:mysql://172.16.10.10:3306/dabc? " +
"user=yy " +
"&password=123 "
+ "&useUnicode=true "
+ "&characterEncoding=UTF-8 ";
Connection conn2= DriverManager.getConnection(url2);
PreparedStatement stt=conn2.prepareStatement( "Select name,city from corporation limit 0,2 ");
ResultSet rs=stt.executeQuery();
while(rs.next())
{
System.out.println(new String(rs.getString( "name ").getBytes( "8859_1 "), "UTF-8 ")+ " " +rs.getString( "city "));
}
stt.close();
}catch(Exception e)
{
System.out.println(e);
}
}
以上代码出来的结果为:
广????达??????????????????????????? ????·????
??山??顺德?????达?????件???????????? ????±±
------解决方案--------------------我也遇到同样问题 帮顶
------解决方案--------------------System.out.println(new String(rs.getString( "name ").getBytes( "8859_1 "), "UTF-8 ")
不用
直接System.out.println(rs.getString( "name)
因为
String url2= "jdbc:mysql://172.16.10.10:3306/dabc? " +
"user=yy " +
"&password=123 "
+ "&useUnicode=true "
+ "&characterEncoding=UTF-8 ";
这里已经设置为UTF-8
乱码是你自己画蛇添足造成的
------解决方案--------------------哦!我也不会这个
------解决方案--------------------mysql里应该是GBK的吧 你把那个不要试试
还有System.out.println(new String(rs.getString( "name ").getBytes( "8859_1 "), "UTF-8 ")+ " " +rs.getString( "city ")); 如果要转的话应该这样写:System.out.println(new String(rs.getString( "name ").getBytes( "iso-8859-0 "), "UTF-8 ")+ " " +rs.getString( "city "));
------解决方案--------------------MYSQL安装时必须设置字符集,
连接时:jdbc:mysql://localhost/shujuku?user=root&password=mfditfyu&useUnicode=true&characterEncoding=GB2312