SQL\u ASCII和Java远程访问PostgreSQL
你好 我试图将请求发送到PostgreSQL 8.x,它使用字符编码SQL\U ASCII。遗憾的是,我无法以任何方式将其转换为UTF-8:既不能使用springframework发送连接属性client_encoding=UTF8,也不能直接在jdbc事务中发送“SET client_encoding='UTF8';”——没有任何帮助 在jdbc事务中设置客户机编码时,我检查了,如果确实设置了客户机编码-是的,在UTF8中确实设置了客户机编码,但是同一会话的下一个语句返回我仍然无法识别的特殊字符SQL\u ASCII和Java远程访问PostgreSQL,java,spring,postgresql,jdbc,character-encoding,Java,Spring,Postgresql,Jdbc,Character Encoding,你好 我试图将请求发送到PostgreSQL 8.x,它使用字符编码SQL\U ASCII。遗憾的是,我无法以任何方式将其转换为UTF-8:既不能使用springframework发送连接属性client_encoding=UTF8,也不能直接在jdbc事务中发送“SET client_encoding='UTF8';”——没有任何帮助 在jdbc事务中设置客户机编码时,我检查了,如果确实设置了客户机编码-是的,在UTF8中确实设置了客户机编码,但是同一会话的下一个语句返回我仍然无法识别的特殊字
con = ds.getConnection();
con.setAutoCommit(false);
stmt = con.prepareStatement("SHOW client_encoding");
ResultSet rs = stmt.executeQuery();
while(rs.next()){
System.out.println(rs.getString(1));
//Here is the output "UNICODE"
}
stmt.close();
stmt = con.prepareStatement("SET client_encoding='UTF8'");
stmt.execute();
stmt.close();
stmt = con.prepareStatement("SHOW client_encoding");
rs = stmt.executeQuery();
while(rs.next()){
System.out.println(rs.getString(1));
//Here is the output "UTF8"
}
stmt.close();
stmt = con.prepareStatement(sql);
ResultSet res = stmt.executeQuery();
while(res.next()) {
String s = res.getString("mycolumn");
System.out.println(s);
//The text has "?" instead of special chars
}
配置:
<bean id="mybean" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<constructor-arg><value>[myurl]</value></constructor-arg>
<constructor-arg>
<props>
<prop key="charSet">SQL_ASCII</prop>
<prop key="client_encoding">UTF-8</prop>
<prop key="timezone">UTC</prop>
<prop key="user">[user]</prop>
<prop key="password">[password]</prop>
<prop key="allowEncodingChanges">true</prop>
</props>
</constructor-arg>
<property name="driverClassName"><value>org.postgresql.Driver</value></property>
</bean>
[我的网址]
SQL\U ASCII
UTF-8
UTC
[用户]
[密码]
真的
org.postgresql.Driver
使用的PostgreSQL驱动程序是PostgreSQL-8.4-701.jdbc4.jar
PostgreSQL中的输入是LATIN1,我也尝试过将编码设置为LATIN1和ISO88591,同样的错误也会发生
现在真的有可能将这种编码转换成任何标准吗
谢谢你的建议 解决方案
我找到了解决办法。应避免转换并直接获取字节:
private String getSqlAscii(ResultSet res, String column) throws SQLException {
byte[] b = res.getBytes(column);
if(b != null) {
try {
return new String(b, "[input-encoding]");
} catch (UnsupportedEncodingException e) {
log.error("Wrong encoding configured", e);
}
}
return null;
}
私有字符串getSqlAscii(ResultSet res,String column)抛出SQLException{
字节[]b=res.getBytes(列);
如果(b!=null){
试一试{
返回新字符串(b,“[input encoding]”);
}捕获(不支持的编码异常e){
日志错误(“配置的编码错误”,e);
}
}
返回null;
}
一个重要的要求是:您应该知道在输入PostgeSQL的数据上使用了什么字符集。这是SQL\u ASCII的弱点,这不是一个解决方案。这是一个解决办法。这使得数据完全不可移植。有解决办法总比没有好。我同意这不太好,但我认为否决票有点苛刻。我发现他的答案很有用。