在 python 中使用 MySQLdb 插入 mysql 后,如何安全有效地获取行 ID?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/706755/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 20:42:31  来源:igfitidea点击:

How do you safely and efficiently get the row id after an insert with mysql using MySQLdb in python?

pythonmysql

提问by grieve

I have a simple table in mysql with the following fields:

我在 mysql 中有一个简单的表,其中包含以下字段:

  • id -- Primary key, int, autoincrement
  • name -- varchar(50)
  • description -- varchar(256)
  • id -- 主键,整数,自增
  • 名称 -- varchar(50)
  • 描述——varchar(256)

Using MySQLdb, a python module, I want to insert a name and description into the table, and get back the id.

使用 MySQLdb,一个 python 模块,我想在表中插入一个名称和描述,并取回 id。

In pseudocode:

在伪代码中:

db = MySQLdb.connection(...)
queryString = "INSERT into tablename (name, description) VALUES" % (a_name, a_desc);"

db.execute(queryString);
newID = ???

回答by David Z

I think it might be

我想可能是

newID = db.insert_id()


Edit by Original Poster

由原始海报编辑

Turns out, in the version of MySQLdb that I am using (1.2.2) You would do the following:

事实证明,在我使用的 MySQLdb 版本 (1.2.2) 中,您将执行以下操作:

conn = MySQLdb(host...)

c = conn.cursor()
c.execute("INSERT INTO...")
newID = c.lastrowid

I am leaving this as the correct answer, since it got me pointed in the right direction.

我将此作为正确答案,因为它让我指出了正确的方向。

回答by Stefano Borini

I don't know if there's a MySQLdb specific API for this, but in general you can obtain the last inserted id by SELECTing LAST_INSERT_ID()

我不知道是否有针对 MySQLdb 的特定 API,但通常您可以通过SELECTing LAST_INSERT_ID()获取最后插入的 id

It is on a per-connection basis, so you don't risk race conditions if some other client performs an insert as well.

它是基于每个连接的,因此如果其他客户端也执行插入操作,您就不会面临竞争条件的风险。

回答by Abdul Bijur V A

You could also do a

你也可以做一个

conn.insert_id

conn.insert_id

回答by TheTXI

The easiest way of all is to wrap your insert with a select count query into a single stored procedure and call that in your code. You would pass in the parameters needed to the stored procedure and it would then select your row count.

最简单的方法是将带有选择计数查询的插入包装到单个存储过程中,并在代码中调用它。您将向存储过程传递所需的参数,然后它会选择您的行数。