getting ids of multiple rows inserted in psycopg2

后端 未结 3 1752
北荒
北荒 2020-12-21 01:27

I\'d like to use psycopg2 to INSERT multiple rows and then return all the ids (in order) using a single query. This is what PostgreSQL\'s RET

3条回答
  •  执念已碎
    2020-12-21 01:47

    Pass the dynamically-generated data as an array of tuples and unnest it

    import psycopg2
    
    insert = """
        insert into my_table (field_1, field_2)
        select field_1, field_2
        from unnest(%s) s(field_1 int, field_2 int)
        returning id
    ;"""
    
    data = [(0,0),(1,1),(2,2)]
    
    conn = psycopg2.connect("host=localhost4 port=5432 dbname=cpn")
    cursor = conn.cursor()
    cursor.execute(insert, (data,))
    print cursor.fetchall()
    conn.commit()
    conn.close()
    

    Prints

    [(1,), (2,), (3,)]
    

提交回复
热议问题