你好,
我尝试将请求发送到具有 SQL_ASCII 字符编码的 PostgreSQL 8.x。遗憾的是,我无法以任何方式将其转换为 UTF-8:既不能使用 springframework 发送连接属性 client_encoding=UTF8,也不能“SET CLIENT_ENCODING = 'UTF8';”直接在 jdbc 事务中 - 没有任何帮助。
在jdbc事务中设置客户端编码时,我检查了是否确实设置了client_encoding - 是的,client_encoding确实以UTF8设置,但同一 session 的下一条语句返回我仍然无法识别的特殊字符。
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>
使用的 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; }
一个重要的要求:您应该知道 PostgeSQL 的数据输入使用了什么字符集。这是 SQL_ASCII 的弱点
关于java - SQL_ASCII 和 Java 远程访问 PostgreSQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3668769/