2011-03-14 100 views
1

嗨,我有一個帶latin1字符集的postgres數據庫和一個表「用戶」。我需要用準備好的語句在java中插入用戶名將java utf-16字符串插入到postgres字符字段中

boolean success = false; 
String query = "INSERT INTO public.user (name,email) VALUES(?,?)"; 
try { 
    PreparedStatement ps; 
    ps = db.prepareStatement(query); 
    ps.setString(1, user.getName()); 
    ps.setString(2, user.getEmail()); 
    if (ps.executeUpdate() != 0) 
    success = true; 
    ps.close(); 
} catch (SQLException ex) { 
} finally { 
    return success; 
} 

問題是,當user.getName()和user.getEmail()中包含像電子口音,O等字符,表存儲怪異的字符。如何將正確的字符序列從java utf-16保存到postgres latin1字符集編碼?

回答

4

你不需要做任何特殊的事情,jdbc驅動程序會爲你處理所有的轉換。但是,問題在於latin1字符集不能編碼所有可用字符(它只支持256個字符)。所以,如果你試圖把它們放在你的桌子上,你會失去某些字符。如果你真的想要存儲國際數據,你必須讓你的表存儲一些unicode的變體(utf8,utf16等)。 (你需要使用一些postgres特定的配置來在數據庫級別解決這個問題)。