java oracle中文亂碼的解決方法:1、將讀到的字符串s,則進(jìn)行純手工轉(zhuǎn)碼,代碼為【new string(s.getbyte(a), b)】;2、使用druid對(duì)各種數(shù)據(jù)庫(kù)驅(qū)動(dòng)做了一層統(tǒng)一的封裝,編碼轉(zhuǎn)換。
【相關(guān)學(xué)習(xí)推薦:java基礎(chǔ)教程】
java oracle中文亂碼的解決方法:
轉(zhuǎn)碼方法
當(dāng)java讀oracle遇到中文亂碼時(shí),我們就需要進(jìn)行轉(zhuǎn)碼。轉(zhuǎn)碼的方法很多,我接觸過(guò)的有以下幾種。
1、純手工轉(zhuǎn)碼
將讀到的字符串s進(jìn)行轉(zhuǎn)碼,如:new string(s.getbyte(a), b)
2、druid
druid是阿里巴巴自己開(kāi)發(fā)的一個(gè)驅(qū)動(dòng),它其實(shí)是對(duì)各種數(shù)據(jù)庫(kù)驅(qū)動(dòng)做了一層統(tǒng)一的封裝,添加日志、告警、編碼轉(zhuǎn)換等功能。配置方式如下:
<bean id="opensqldatasource"class="org.apache.commons.dbcp.basicdatasource"destroy-method="close"><property name="driverclassname" value="com.alibaba.china.jdbc.simpledriver" /><property name="url" value="jdbc:oracle:thin:@10.20.130.210:1521:dwtest" /><property name="username" value="etl" /><property name="password" value="etl" /><property name="connectionproperties"><value>serverencoding=iso-8859-1;clientencoding=gbk;defaultrowprefetch=50;bigstringtryclob=true</value></property></bean>其中connectionproperties中包含serverencoding、clientencoding兩個(gè)屬性。在java讀取到數(shù)據(jù)后,如果發(fā)現(xiàn)serverencoding、clientencoding不同,則會(huì)自動(dòng)進(jìn)行如下編碼轉(zhuǎn)換。
new string(s.getbyte(serverencoding), clientencoding)3、weblade ibatis callback
它采用了如下注冊(cè)ibatis callback的方式。
<bean id="sqlmapexecutordelegate"class="com.asc.alibaba.dao.ibatis.sqlmap.engine.impl.sqlmapexecutordelegate"><property name="mappedstatementstrategy" ref="mappedstatementstrategy" /><property name="handlerlist"><list><ref bean="stringhandler" /><!-- <ref bean="objecthandler" />--></list></property></bean><bean id="stringhandler" class="com.asc.alibaba.dao.ibatis.handler.typehandleradapter"><property name="javatype" value="java.lang.string" /><property name="handlercallback" ref="stringtypehandlercallback" /></bean>使得在默認(rèn)情況下,程序會(huì)把ibatis獲取到的string進(jìn)行如下編碼轉(zhuǎn)換:
new string(s.getbyte(“iso-8859-1”), “gbk”)該二方庫(kù)引入的方式如下:
<dependency><groupid>com.alibaba.asc.shared</groupid><artifactid>weblade.core.ibatisext</artifactid><version>1.2.0-snapshot</version></dependency>ibatis callback隱藏了編碼轉(zhuǎn)換的過(guò)程,但問(wèn)題是它對(duì)項(xiàng)目中所有的數(shù)據(jù)源生效。使得無(wú)法同時(shí)透明地支持需要轉(zhuǎn)碼和無(wú)需轉(zhuǎn)碼的數(shù)據(jù)源。
相關(guān)推薦:編程視頻課程