如何在Python中向MySQL数据库插入后获取“id”?

238 投票
5 回答
225896 浏览
提问于 2025-04-15 21:03

我执行了一个插入数据的命令

cursor.execute("INSERT INTO mytable(height) VALUES(%s)",(height))

我想要获取这个新插入数据的主键。

我的表有两列:

id      primary, auto increment
height  this is the other column.

我该怎么获取“id”,在我刚插入数据之后?

5 个回答

42

Python的数据库API规范还定义了游标对象的'lastrowid'属性,所以...

id = cursor.lastrowid

...这也应该可以用,而且显然是基于每个连接的。

136

另外,cursor.lastrowid(这是一个dbapi/PEP249的扩展,MySQLdb支持它):

>>> import MySQLdb
>>> connection = MySQLdb.connect(user='root')
>>> cursor = connection.cursor()
>>> cursor.execute('INSERT INTO sometable VALUES (...)')
1L
>>> connection.insert_id()
3L
>>> cursor.lastrowid
3L
>>> cursor.execute('SELECT last_insert_id()')
1L
>>> cursor.fetchone()
(3L,)
>>> cursor.execute('select @@identity')
1L
>>> cursor.fetchone()
(3L,)

cursor.lastrowid的使用成本比connection.insert_id()低一些,而且比再次请求MySQL要便宜得多。

335

使用 cursor.lastrowid 可以获取在这个游标对象上最后插入的行的ID,或者使用 connection.insert_id() 来获取在这个连接上最后插入的ID。

撰写回答