Postgres在字符之间插入带有null的字符串

时间:2016-03-08 22:30:18

标签: postgresql jdbc varchar

我有一个表,其中数据可能在字符之间包含null。因为我已经将表定义为VARCHAR,所以它会抛出一个错误

  

org.postgresql.util.PSQLException:错误:无效的字节序列   编码“UTF8”:0x00

应该有一种方法可以在postgres中插入基于null的字符串。 这是插入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上处理得很好。

1 个答案:

答案 0 :(得分:1)

您不能在PostgreSQL中的字符串中包含null。来自documentation

  

代码为零的字符不能是字符串常量。

Java使用稍微modified Unicode方案,其中U+0000可以编码为0xC0 0x80,这是一个双字节编码。您可以在字符串中替换这些值,而不是二进制null。 PostgreSQL很乐意接受它。