Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to insert null in bytea field in postgres

I am unable to insert a null value in my postgres database where the datatype is bytea(blob). This is my code snippet from java:

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

The bytea column is a nullable column. The following is the table description.

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

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

description | bytea |           | extended |              | 

Has OIDs: no

I am getting the following exception java.sql.BatchUpdateException: Batch entry 11 INSERT INTO public.plan(description) VALUES(NULL) was aborted. Call getNextException to see the cause.

like image 715
Poulami Avatar asked Dec 07 '15 07:12

Poulami


People also ask

What is Bytea in PostgreSQL?

The bytea data type allows the storage of binary strings or what is typically thought of as “raw bytes”. Materialize supports both the typical formats for input and output: the hex format and the historical PostgreSQL escape format. The hex format is preferred.

Does Null value occupy space in PostgreSQL?

Answer: No, Each null value only uses one bit on disk.

Can we store bytes in PostgreSQL?

PostgreSQL provides two distinct ways to store binary data. Binary data can be stored in a table using the data type bytea or by using the Large Object feature which stores the binary data in a separate table in a special format and refers to that table by storing a value of type oid in your table.

Can we store blob in PostgreSQL?

Blob (Binary large object) is an Oracle data type that is used to store binary data like contents of a file or information like audio, video, and images. PostgreSQL does not have the Blob data type directly, but we can work with it using the methods below.


1 Answers

Postgres has two different "BLOB" types: bytea, which is essentially what the SQL standard defines as a BLOB. And "large objects" which is more or less a "pointer" to binary storage (it's still stored inside the DB).

The Postgres JDBC has always treated "large objects" as the equivalent to BLOB (which I have never understood) and thus ps.setNull(++index, java.sql.Types.BLOB); makes the driver think you are dealing with a "large object" (aka "oid") column.

To overcome this, use

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

alternatively you can use:

ps.setObject(++index, null);
like image 57
a_horse_with_no_name Avatar answered Nov 04 '22 20:11

a_horse_with_no_name