psycopg2: insert multiple rows with one query

后端 未结 15 2287
谎友^
谎友^ 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:42

    I've been using ant32's answer above for several years. However I've found that is thorws an error in python 3 because mogrify returns a byte string.

    Converting explicitly to bytse strings is a simple solution for making code python 3 compatible.

    args_str = b','.join(cur.mogrify("(%s,%s,%s,%s,%s,%s,%s,%s,%s)", x) for x in tup) 
    cur.execute(b"INSERT INTO table VALUES " + args_str)
    

提交回复
热议问题