完美解决Kettle导数据库产生的中文乱码

来源:互联网 发布:淘宝v4是什么意思 编辑:程序博客网 时间:2024/06/06 15:36
如果公司内一开始没有好好规划数据库建设,那么后期可能存在多种字符集的数据库实例。在做数据仓库或者来回导数据的时候,因字符集导致中文乱码问题困扰着不少人。网上有很多前辈们总结的解决中文乱码的方案,关于使用kettle如何解决也有一两篇谈到在建数据库连接时加characterEncoding来解决。我昨晚找到另外一种方式来跟大家分享:

 

经过对源码搜索”encoding“,找一句注释,发现其实解决方法很简单,

Java代码 复制代码 收藏代码
  1. /**  
  2.  * Build the row using ResultSetMetaData rsmd  
  3.     * @param rm The resultset metadata to inquire 
  4.     * @param ignoreLength true if you want to ignore the length (workaround for MySQL bug/problem) 
  5.     * @param lazyConversion true if lazy conversion needs to be enabled where possible 
  6.  */  
  7. private RowMetaInterface getRowInfo(ResultSetMetaData rm, boolean ignoreLength, boolean lazyConversion) throws KettleDatabaseException   
  8. {   
  9.        if (rm==nullreturn null;   
  10.        
  11.     rowMeta = new RowMeta();   
  12.        
  13.     try  
  14.     {   
  15.         // TODO If we do lazy conversion, we need to find out about the encoding  
  16.         //   
  17.            int fieldNr = 1;   
  18.         int nrcols=rm.getColumnCount();    
  19.         for (int i=1;i<=nrcols;i++)   
  20.         {   
  21.             String name=new String(rm.getColumnName(i));   
  22.                   
  23.                // Check the name, sometimes it's empty.  
  24.                //   
  25.                if (Const.isEmpty(name) || Const.onlySpaces(name))   
  26.                {   
  27.                    name = "Field"+fieldNr;   
  28.                    fieldNr++;   
  29.                }   
  30.                   
  31.             ValueMetaInterface v = getValueFromSQLType(name, rm, i, ignoreLength, lazyConversion);   
  32.             rowMeta.addValueMeta(v);               
  33.         }   
  34.         return rowMeta;   
  35.     }   
  36.     catch(SQLException ex)   
  37.     {   
  38.         throw new KettleDatabaseException("Error getting row information from database: ", ex);   
  39.     }   
  40. }  

 就是这样”If we do lazy conversion, we need to find out about the encoding“,直接勾选”允许延迟转换“即可:

这样在从数据库读取的数据就能保持原有字符集,不因默认强制使用utf8导致乱码,在输出时指定文件字符集,就会解决导出到文件中的乱码问题。

如果导入到目标表的字符集与源表不同,需要在入库前用select values做字符转换(纯属废话,相同就不会有乱码了):

 

整个流程如下

这样,无论到文件还是目标表,都不会再有乱码了。

 

 

如果以上还无法解决,可以在Table Input 和Table Output的数据库连接高级选项中设置当前session的字符集;以下除了可以设置session 的字符集,还可以设置日期格式等。

 

通过以上设置还无法解决,只能归结为RP不好了O(∩_∩)O~

0 0