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), (3, 4), (5, 6);
The only way I know is
args = [(1,2), (3,4), (5,6)]
args_str = ','.join(cursor.mogrify("%s", (x, )) for x in args)
cursor.execute("INSERT INTO t (a, b) VALUES "+args_str)
but I want some simpler way.
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:
It is array, which may contain any amount of objects inside. Then your SQL looks like:
Notice: Your postgress must be new enough, to support json