psycopg2: insert multiple rows with one query

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

    If you're using SQLAlchemy, you don't need to mess with hand-crafting the string because SQLAlchemy supports generating a multi-row VALUES clause for a single INSERT statement:

    rows = []
    for i, name in enumerate(rawdata):
        row = {
            'id': i,
            'name': name,
            'valid': True,
        }
        rows.append(row)
    if len(rows) > 0:  # INSERT fails if no rows
        insert_query = SQLAlchemyModelName.__table__.insert().values(rows)
        session.execute(insert_query)
    

提交回复
热议问题