最近我們將mysql db從Latin1移動到UTF8。在嘗試了幾種不同的方法來轉換它之後,我們無法找到任何沒有引入一些非常糟糕的數據信息的命令(而且很多都沒有做任何事情)。使用chardet檢測具有JDBC的MySQL數據庫中的錯誤編碼
這讓我想知道是否有很多不同的編碼正在進行,因爲似乎沒有涵蓋我們的測試用例(數據庫中的各種帖子)的單一方法。爲了測試這個理論,我編寫了一個小型的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就是其中之一,不管你如何檢索它,它就是這樣(有趣的角色和所有)?
謝謝!
根據['character_set_connection'](http://dev.mysql.com/doc/refman/5.5/en/server-system-variables.html#sysvar_character_set_connection)和['character_set_database'](http: //dev.mysql.com/doc/refman/5.5/en/server-system-variables.html#sysvar_character_set_database)設置MySQL將嘗試執行轉換。如果你的數據已經打破了符號,我想你需要事先知道什麼是源編碼來處理這個問題。或者嘗試將您的字段轉換爲「BLOB」? –
是的,這是現在棘手的部分。其中的一些數據是UTF8,一些是Latin1,上帝知道那裏還有什麼(這是一個相當老的數據庫,有幾個內容系統連接到它)。所以,當我嘗試blob技術時,它轉換了一些奇妙和截斷的其他。 :(因此,我試圖首先檢測然後轉換。看起來在JDBC和MySQL之間的所有約定的字符集是什麼都會在(這是有道理的,只是不幫助我。哈) – bnferguson
嘗試' your_field as binary)'。MySQL連接器應該返回'byte []'。 –