psycopg2: insert multiple rows with one query

后端 未结 15 2310
谎友^
谎友^ 2020-11-22 09:11

I need to insert multiple rows with one query (number of rows is not constant), so I need to execute query like this one:

INSERT INTO t (a, b) VALUES (1, 2),         


        
15条回答
  •  遇见更好的自我
    2020-11-22 09:39

    Another nice and efficient approach - is to pass rows for insertion as 1 argument, which is array of json objects.

    E.g. you passing argument:

    [ {id: 18, score: 1}, { id: 19, score: 5} ]
    

    It is array, which may contain any amount of objects inside. Then your SQL looks like:

    INSERT INTO links (parent_id, child_id, score) 
    SELECT 123, (r->>'id')::int, (r->>'score')::int 
    FROM unnest($1::json[]) as r 
    

    Notice: Your postgress must be new enough, to support json

提交回复
热议问题