欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

mysql latin1 转 utf8 中文乱码

程序员文章站 2024-01-26 22:45:28
...

环境:mysql数据库字符集为:latin1

           java web项目连接数据库为:utf-8

中文乱码解决办法:

插入时:把插入内容转为unicode,再插入数据库

查询时:把latin1查询结果转成unicode,再从unicode转成utf-8

 

/**
	 * latin1字符集转换为UTF-8
	 * @param s
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public static String latin1ToUtf8(String s) 
	{
		if (s != null)
        {
            try
            {
                int length = s.length();
                byte[] buffer = new byte[length];
                //0x81 to Unicode 0x0081, 0x8d to 0x008d, 0x8f to 0x008f, 0x90 to 0x0090, and 0x9d to 0x009d.
                //Mysql 的latin1 不等于标准的latin1(iso-8859-1) 和cp1252,
                //比iso-8859-1多了0x80-0x9f字符,比cp1252多了0x81,0x8d,0x8f,0x90,0x9d 一共5个字符
                for (int i = 0; i < length; ++i)
                {
                    char c = s.charAt(i);
                    if (c == 0x0081)
                    {
                        buffer[i] = (byte) 0x81;
                    }
                    else if (c == 0x008d)
                    {
                        buffer[i] = (byte) 0x8d;
                    }
                    else if (c == 0x008f)
                    {
                        buffer[i] = (byte) 0x8f;
                    }
                    else if (c == 0x0090)
                    {
                        buffer[i] = (byte) 0x90;
                    }
                    else if (c == 0x009d)
                    {
                        buffer[i] = (byte) 0x9d;
                    }
                    else
                    {
                        buffer[i] = Character.toString(c).getBytes("CP1252")[0];
                    }
                }
                String result = new String(buffer, "UTF-8");
                return result;
            }
            catch (UnsupportedEncodingException e)
            {
                e.printStackTrace();
            }
        }
        return null;
	}