Java 读取 MySQL 中文 乱码

本文详细介绍了在Java应用中通过Eclipse读取MySQL数据库时遇到的中文乱码问题及其解决办法。重点讲解了如何正确地处理字符串编码,确保数据在不同系统间的正确传输。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Java 读取 MySQL 中文 乱码

场景:Java,eclipse,读取MySQL数据库,MySQL编码为utf-8

问题:读出来的中文在eclipse的输出窗口中显示为乱码

 

错误的写法

1

 

   System.out.print(new String( rs.getString("bib_author").getBytes("utf-8"),"GBK" )); 

 

   System.out.print( rs.getString("bib_author")); 

 

Java中统一使用Unicode编码。

 

正确的写法:

 

System.out.print(new String (rs.getBytes("bib_author"),"utf-8") + " "); 

 

如划线加粗部分所示,应该先用二进制方式读进来,然后再转化为utf-8方式,和数据库中的编码一致。

 

 

下面是之前碰到过的一个例子,从web服务器读取数据,并转化为utf-8。web服务器使用的是iso-8859-1编码。

同样也是先用getbytes方式先获取二进制流,然后转成utf-8。

-------------------------------------------------------------------------------------------

3个地方设置编码,解决乱码问题

    public static String GetResponse(HttpMethodBase Method) throws IOException {
        String charset= Method.getResponseCharSet();
        System.out.println("返回的字符编码为:"+charset);
        InputStream responseBody = Method.getResponseBodyAsStream();
//        BufferedReader br = new BufferedReader(new InputStreamReader(responseBody));
        BufferedReader br = new BufferedReader(new InputStreamReader(Method.getResponseBodyAsStream(), "ISO-8859-1"));//1 
        String tempbf;
        StringBuffer htmlbf = new StringBuffer(100);
        while ((tempbf = br.readLine()) != null) {
//            htmlbf.append(tempbf);
            htmlbf.append(new String(tempbf.getBytes("iso-8859-1"),"utf-8"));//2 
            htmlbf.append("/n");
        }
        return htmlbf.toString();
    }//end GetResponse

然后在构建GetMethod或PostMethod时也指定编码

          Method.addRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8");//3

或者        NameValuePair p2 = new NameValuePair( "Content-Type","text/html; charset=utf-8");

post.setRequestBody( new NameValuePair[]{p2})//3

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值