环境: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;

}

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐