getting ids of multiple rows inserted in psycopg2

后端 未结 3 1758
北荒
北荒 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

    The trick is to use mogrify. It uses a single execute and id therefore faster than executemany anyways:

    def insert_many(self, table: str, id_column: str, values: list):
        if not values:
            return []
    
        keys = values[0].keys()
        query = cursor.mogrify("INSERT INTO {} ({}) VALUES {} RETURNING {}".format(
                table,
                ', '.join(keys),
                ', '.join(['%s'] * len(values)),
                id_column
            ), [tuple(v.values()) for v in values])
    
        conn = psycopg2.connect("host=localhost4 port=5432 dbname=cpn")
        cursor = conn.cursor()
        cursor.execute(query)
        return [t[0] for t in (cursor.fetchall()]
    

提交回复
热议问题