无法在 postgres 的 bytea 字段中插入空值

Unable to insert null in bytea field in postgres

我无法在数据类型为 bytea(blob) 的 postgres 数据库中插入空值。这是我来自 java 的代码片段:

ps.setNull(++index, java.sql.Types.BLOB);

bytea 列是可为空的列。以下是table的说明。

testdb=# \d+ plan 
                           Table "public.plan"
   Column    | Type  | Modifiers | Storage  | Stats target | Description 

-------------+-------+-----------+----------+--------------+-------------

description | bytea |           | extended |              | 

Has OIDs: no

我收到以下异常 java.sql.BatchUpdateException:批处理条目 11 INSERT INTO public.plan(description) VALUES(NULL) 已中止。调用 getNextException 查看原因。

Postgres 有两种不同的 "BLOB" 类型:bytea,本质上就是 SQL 标准定义的 BLOB。 "large objects" 或多或少是二进制存储的 "pointer" (它仍然存储在数据库中)。

Postgres JDBC 一直将 "large objects" 视为等同于 BLOB(我从未理解过),因此 ps.setNull(++index, java.sql.Types.BLOB); 使驱动程序认为您正在处理带有 "large object"(又名 "oid")列。

要克服这个问题,请使用

ps.setNull(++index, Types.OTHER);

或者您可以使用:

ps.setObject(++index, null);

这对我也有用:

ps.setNull(++index, Types.BINARY);