将java utf-16字符串插入postgres字符字段
你好,我有一个带有 latin1 字符集的 postgres 数据库和一个表“user”。我需要在java中使用准备好的语句插入用户名
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()包含带重音符号的字符时,如è,ò等,表存储奇怪的字符。如何将正确的字符序列从 java utf-16 保存为 postgres latin1 字符集编码?
HI, I have a postgres database with latin1 charset, and a table "user". I need to insert the name of the users using a prepared statement in java
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;
}
The problem is when user.getName() and user.getEmail() contains characters with accents like è,ò, and so on, the table store weird characters. How can save the right characters sequence from java utf-16 to postgres latin1 charset encoding?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您不需要做任何特殊的事情,jdbc 驱动程序会为您处理所有转换。然而,问题在于 latin1 字符集无法对所有可用字符进行编码(它仅支持 256 个字符)。因此,如果您尝试将某些字符放入表中,您将丢失某些字符。如果您真的想存储国际数据,则必须让您的表存储某种 unicode 变体(utf8、utf16 等)。 (您需要使用一些 postgres 特定配置在数据库级别修复此问题)。
you don't need to do anything special, the jdbc driver handles all the conversions for you. the problem, however, is that the latin1 charset cannot encode all available characters (it only supports 256 characters). so, you will lose certain characters if you attempt to put them in your table. if you are serious about storing international data, you must make your tables store some variant of unicode (utf8, utf16, etc). (you would need to fix this at the database level using some postgres specific configuratino).
jtahlborn 对你的问题是正确的。
看看 http://www.postgresql.org/docs/8.2/static /multibyte.html 了解 postgre 中的多字节编码。
jtahlborn is right about your problem.
Take a look at http://www.postgresql.org/docs/8.2/static/multibyte.html to understand multibyte encodings in postgre.