Python Postgresql insert multiple rows with bytea in a single execution

61 views Asked by At

I am looking to make a batch insert into a postgres table where one column is type bytea.

I suspect the issue is the f-string substitution, It seems it would work if there is a way to do the value substitution as part of the cur.execute() call.

Table looks like this:

CREATE TABLE queue (
    id INTEGER NOT NULL PRIMARY KEY GENERATED ALWAYS AS IDENTITY,
    queue_date TIMESTAMPTZ DEFAULT now(),
    file_id BIGINT NOT NULL,
    content_type CHARACTER VARYING( 255 ),
    source BYTEA
);

This is not ideal:

for i, (fileId, storeDate, contentType, source) in enumerate(fileData):
    cur.execute("INSERT INTO ocr_process_queue(file_id, content_type, source) VALUES (%s, '%s', %s)", (fileId, contentType, source))

What I did:

query = "INSERT INTO queue(file_id, content_type, source) VALUES "
for i, (fileId, storeDate, contentType, source) in enumerate(fileData):
    query += f"""(%s,'%s',%s)""" % (fileId, contentType, source)
    query += "," if i < len(fileData) - 1 else ";"
print(query)
# INSERT INTO queue(file_id, content_type, source) VALUES (114,'text/html',<memory at 0x16968a880>),....,(100,'text/plain',<memory at 0x16968a940>);

cur.execute(query)
0

There are 0 answers