mysql中blob类型乱码怎么办
不懂mysql中blob类型乱码怎么办?其实想解决这个问题也不难,下面让小编带着大家一起学习怎么去解决,希望大家阅读完这篇文章后大所收获。
场景:数据库为mysql该字段的类型blob。
在从数据库读取时是保存内容全部为乱码,最后在网上找到一种好的解决方法。
可以在读出内容后自己写代码去转换
1、写一个转换类,在指定结果类型时给需要转换的字段指定装换类(PS:持久层使用了mybatis)
importjava.io.ByteArrayInputStream;importjava.io.UnsupportedEncodingException;importjava.sql.Blob;importjava.sql.CallableStatement;importjava.sql.PreparedStatement;importjava.sql.ResultSet;importjava.sql.SQLException;importorg.apache.ibatis.type.BaseTypeHandler;importorg.apache.ibatis.type.JdbcType;publicclassMyBlobTypeHandlerextendsBaseTypeHandler<String>{//###指定字符集privatestaticfinalStringDEFAULT_CHARSET="utf-8";publicvoidsetNonNullParameter(PreparedStatementps,inti,Stringparameter,JdbcTypejdbcType)throwsSQLException{ByteArrayInputStreambis;try{//###把String转化成byte流bis=newByteArrayInputStream(parameter.getBytes(DEFAULT_CHARSET));}catch(UnsupportedEncodingExceptione){thrownewRuntimeException("BlobEncodingError!");}ps.setBinaryStream(i,bis,parameter.length());}@OverridepublicStringgetNullableResult(ResultSetrs,StringcolumnName)throwsSQLException{Blobblob=(Blob)rs.getBlob(columnName);byte[]returnValue=null;if(null!=blob){returnValue=blob.getBytes(1,(int)blob.length());}try{//###把byte转化成stringreturnnewString(returnValue,DEFAULT_CHARSET);}catch(UnsupportedEncodingExceptione){thrownewRuntimeException("BlobEncodingError!");}}publicStringgetNullableResult(CallableStatementcs,intcolumnIndex)throwsSQLException{Blobblob=(Blob)cs.getBlob(columnIndex);byte[]returnValue=null;if(null!=blob){returnValue=blob.getBytes(1,(int)blob.length());}try{returnnewString(returnValue,DEFAULT_CHARSET);}catch(UnsupportedEncodingExceptione){thrownewRuntimeException("BlobEncodingError!");}}@OverridepublicStringgetNullableResult(ResultSetrs,intcolumnIndex)throwsSQLException{//TODOAuto-generatedmethodstubreturnnull;}}
2、在mybatis配置文件中指定
<resultcolumn="settlementContent"property="settlementContent"typeHandler="cn.xxx.utils.MyBlobTypeHandler"/>
感谢你能够认真阅读完这篇文章,希望小编分享mysql中blob类型乱码怎么办内容对大家有帮助,同时也希望大家多多支持亿速云,关注亿速云行业资讯频道,遇到问题就找亿速云,详细的解决方法等着你来学习!
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。