我的mysql字符编码都是utf-8,如下图,可用命令查看mysql的编码类型:
在
mysql客户端查询结果时,中文能正常显示,如下图:
但是当在java程序中读取数据的时候,note字段读出来是乱码,(note字段是Blob类型的),上网查看了许多方法,下面这种方式能正确转换为java中的String类型:
while (rs.next()) {
int id = rs.getInt(1);
String name = rs.getString(2);
int age = rs.getInt(3);
Date birthday = rs.getDate(4);
Blob noteBlob = rs.getBlob(5);
String note = null;
if(noteBlob != null){
InputStream is = noteBlob.getBinaryStream();
ByteArrayInputStream bais = (ByteArrayInputStream)is;
byte[] byte_data = new byte[bais.available()]; //bais.available()返回此输入流的字节数bais.read(byte_data, 0,byte_data.length);//将输入流中的内容读到指定的数组
note = new String(byte_data,"utf-8"); //再转为String,并使用指定的编码方式
is.close();
}