【问题标题】:Postgres insert strings with null between the charactersPostgres在字符之间插入带有null的字符串
【发布时间】:2016-06-23 02:29:15
【问题描述】:

我有一个表格,其中的数据可能在字符之间包含空值。因为我已经将表定义为 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 上处理得很好。

【问题讨论】:

    标签: postgresql jdbc varchar


    【解决方案1】:

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

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

    Java 使用了一种略带modified Unicode 的方案,其中U+0000 可以编码为0xC0 0x80,即两字节编码。您可以替换字符串中的这些值,而不是二进制空值。 PostgreSQL 很乐意接收它。

    【讨论】:

    • 我明白了。可以在后端用任何其他分隔符或不会使用的代码点替换它吗?
    • 用 \uC080 替换 \0 没有帮助,因为它代表 삀。它写为'Te삀t0'。我希望后端用户在不应该在表中表示的地方运行查询。这种情况下WIN1252会有帮助吗?
    • 在 utf-8 U+C080 扩展为 0xEC 0x82 0x80。您不应直接插入该代码点,而应仅插入构成代码点的两个字节。
    猜你喜欢
    • 1970-01-01
    • 2022-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-05
    相关资源
    最近更新 更多