插入多个条目后获取主键列表

2024-09-29 17:15:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用python模块MySQLDb一次插入多个条目(有时最多300个)。看起来像我的sql。。。在

INSERT INTO MyTable (row2,row3) values 
(row2_entry1,row3_entry1),(row2_entry2,row3_entry2),........(row2_entry300,row3_entry300)

此表的主键是自动递增的。我想要的是输入到表中的条目的主键列表。我如何处理一批


Tags: 模块目的sqlmytable条目insertvaluesrow2
1条回答
网友
1楼 · 发布于 2024-09-29 17:15:02

MySQL的LAST_INSERT_ID()只返回一个值。如果是批量插入,则返回第一个插入行的主键值。在

您可以使用GUID标记来跟踪作为批插入操作一部分的行。向表中添加一个额外的varchar(32)列,名为batch_insert_id。执行批插入时,请使用已知的GUID值。插入后,执行select查询以获取插入行的主键。在

import uuid

batch_insert_id = uuid.uuid4().hex
# Execute your batch insert query, with batch_insert_id 
# as value of batch_insert_id for all rows
cursor.execute("SELECT id FROM mytable WHERE batch_insert_id = '%s'", (batch_insert_id,))
primary_keys = [row[0] for row in cursor.fetchall()]

相关问题 更多 >

    热门问题