2016-03-08 133 views
0

我得到一个表,其中数据可能在字符之间包含空值。正如我已经定义的表为VARCHAR,它会引发我一个错误Postgres在字符之间插入字符串为空

org.postgresql.util.PSQLException: ERROR: invalid byte sequence for encoding "UTF8": 0x00

应该有办法,我可以插入Postgres的基于空字符串。 这同时插入到Postgres的

private void postGrestest() throws ClassNotFoundException, SQLException 
{ 
    Class.forName("org.postgresql.Driver"); 

    String dropStmt = "DROP TABLE PUBLIC.TEST"; 
    String createStmt = "CREATE TABLE PUBLIC.TEST(COL1 VARCHAR(50), COL2 BOOLEAN)"; 
    String insertStmt = "INSERT INTO PUBLIC.TEST VALUES (?, ?)"; 
    try (Connection connection = DriverManager.getConnection(
      "jdbc:postgresql://url:5432/objectserver?stringtype=unspecified", 
      "username", "password"); 
      Statement stmt = connection.createStatement(); 
      PreparedStatement ps = connection.prepareStatement(insertStmt);) 
    { 
     stmt.execute(dropStmt); 
     stmt.execute(createStmt); 
     Random r = new Random(); 
     for (int i = 0; i < 100; i++) 
     { 
      Object str = "Test" + i; 
      str = ((String) str).replace('s', '\0'); 
      logger.info("Inserting " + str); 
      // str = ((String) str).replace("\0", ""); 
      ps.setObject(1, str); 
      Object obj = String.valueOf(r.nextBoolean()); 
      ps.setObject(2, obj); 
      ps.executeUpdate(); 
     } 
    } 
} 

样品插入已失败是否有处理这种类型的数据,之前的任何考虑?这个数据是一个基于字符串的数据,其中源可能包含它们之间包含null的数据。这在使用NVARCHAR的不同数据库实例SQL Server上处理得很好。

回答

0

您不能在PostgreSQL的字符串中包含空值。从documentation

The character with the code zero cannot be in a string constant.

Java使用一个稍微modified Unicode方案,其中U+0000可以被编码为0xC0 0x80,两个字节的编码。您可以在字符串中替换这些值而不是二元空值。 PostgreSQL会很乐意接收它。

+0

我明白。这可以在后端用任何其他分隔符或不使用的代码点替换吗? – dmachop

+0

查看更新的答案。 – Patrick

+0

用\ uC080替换\ 0并不能解决问题,因为它代表了삀。它写为'Te삀t0'。我希望后端用户在不应该在表格中表示的位置运行查询。在这种情况下WIN1252会有帮助吗? – dmachop