java - SQL_ASCII 和 Java 远程访问 PostgreSQL

标签 java spring postgresql jdbc character-encoding

你好,

我尝试将请求发送到具有 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/

相关文章:

java - 在Eclipse 导出的jar 的根目录中查找文件以进行JUNIT 测试

java - 如何从android中的字符串文件填充微调器

java - 如何执行spring-boot :run from terminal for Remote Debugging

java - 从 Junit Test 运行时 Spring Boot 应用程序抛出异常

ruby-on-rails - Rails 在基于 Rancher 的 Docker 环境和 Postgresql 中运行缓慢

postgresql - 从 Filemaker 中的更改更新 PostgreSQL 数据库

java - 哪个 jar 文件包含 org.n52.wps.server.observerpattern.ISubject 以及如何下载它?

java - 如何遍历LinkedTreeMap<String, Object>的所有值?

java - 如何通过流式休息提供大文件?

python - 在 Flask-SQLAlchemy 和 Celery 的 celery 任务中正确管理 postgresql 连接