使用chardet通过JDBC检测MySQL数据库中的错误编码

时间:2011-09-26 22:28:09

标签: java mysql scala jdbc

最近我们将mysql数据库从Latin1移到了UTF8。在尝试了几种不同的方法来转换它之后,我们无法找到任何不会引入一些非常令人讨厌的数据集(并且很多都没有做任何事情)。

这让我想知道我们是否有很多不同的编码正在进行,因为似乎没有一种方法可以覆盖我们的测试用例(我们数据库中的各种帖子)。为了测试这个理论,我写了一个小scala应用程序(我的第一个,随意取笑它是如何拼凑和非惯用的!:D)使用chardet查看帖子并告诉我编码。

只有一个问题,一切都是UTF8。

以下是代码:

package main.scala

import org.mozilla.universalchardet.UniversalDetector
import java.sql.DriverManager

object DBConvert {
  def main(args: Array[String]) {
    val detector = new UniversalDetector(null)
    val db_conn_str = "jdbc:mysql://localhost:3306/mt_pre?user=root"
    val connection = DriverManager.getConnection(db_conn_str)

    try {
        val statement = connection.createStatement()
        val rs = statement.executeQuery("SELECT * FROM mt_entry where entry_id = 3886")
        while (rs.next) {
           val buffer = rs.getBytes("entry_text_more")
           detector.handleData(buffer, 0, buffer.length)
           detector.dataEnd()

           val encoding:String = detector.getDetectedCharset;

           if (encoding != null) println("Detected encoding = " + encoding) else println("No encoding detected.");

           detector.reset();

           // Just so we can see the output
           println(rs.getString("entry_text_more"))
        }
    } catch {
      case _ => e: Exception => println(e.getMessage)
    }
    finally {
        connection.close()
    }
  }
}

我试过传递useUnicode的JDBC查询字符串,也就是characterEncoding。他们都没有让UTF-8一直走出来。还尝试使用getBinaryStream和其他,仍然是UTF-8。

完全承认角色编码会使我的头部弯曲一点并且使用新语言可能不是解决此问题的最佳方法。 :)那说我很好奇 - 有没有办法从数据库中获取数据并检测它放在那里的编码,或者它是其中之一,因为它在数据库中编码为UTF-8 ,无论你如何检索它,它是什么(有趣的人物和所有)?

谢谢!

2 个答案:

答案 0 :(得分:1)

一旦我遇到类似的问题。见answer。在连接字符串中设置编码可能会有所帮助。

答案 1 :(得分:0)

请注意,Table Charset和Connection CHarset以及默认数据库编码都是相同的UTF-8。我有一个实例,其中Datbases默认是UTF-8,但表coloumns仍然拉丁语,所以我有一些问题。请查看是否属实。