【问题标题】:SQL_ASCII and Java remote access to PostgreSQLSQL_ASCII 和 Java 远程访问 PostgreSQL
【发布时间】:2011-04-09 18:52:10
【问题描述】:

你好,

我尝试将请求发送到具有字符编码 SQL_ASCII 的 PostgreSQL 8.x。遗憾的是,我无法以任何方式将其转换为 UTF-8:既不能使用 springframework 发送连接属性 client_encoding=UTF8,也不能“SET CLIENT_ENCODING = 'UTF8';”直接在 jdbc 事务中 - 没有任何帮助。

在我检查过在 jdbc 事务中设置客户端编码时,如果真的设置了 client_encoding - 是的,client_encoding 确实设置在 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>

使用的 PostgreSQL-Driver 是 postgresql-8.4-701.jdbc4.jar

PostgreSQL 中的输入是 LATIN1,我也尝试通过将编码设置为 LATIN1 和 ISO88591 - 发生同样的错误。

现在真的可以将此编码转换为任何标准吗?

谢谢你的建议!

【问题讨论】:

    标签: java spring postgresql jdbc character-encoding


    【解决方案1】:

    解决方案

    我已经找到了解决方案。您应该避免转换并直接获取字节:

    私有字符串 getSqlAscii(ResultSet res, String column) 抛出 SQLException { byte[] b = res.getBytes(column); 如果(b!= null){ 尝试 { return new String(b, "[input-encoding]"); } 捕捉(UnsupportedEncodingException e){ log.error("配置错误的编码", e); } } 返回空值; }

    一个重要的要求:你应该知道,在 PostgeSQL 的数据输入中使用了什么字符集。这是 SQL_ASCII 的弱点

    【讨论】:

    • 这不是解决方案。这是一种解决方法。这使得数据完全不可移植。
    • 解决方法总比没有好。我同意它不是很好,但我认为否决票有点苛刻。我发现他的回答很有用。
    猜你喜欢
    • 2021-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多