使用Python INSERT进入MySQL数据库后如何获得"id"?

TIM*_*MEX 169 python mysql database

我执行INSERT INTO语句

cursor.execute("INSERT INTO mytable(height) VALUES(%s)",(height))
Run Code Online (Sandbox Code Playgroud)

我想获得主键.

我的表有2列:

id      primary, auto increment
height  this is the other column.
Run Code Online (Sandbox Code Playgroud)

在我刚插入之后如何获得"id"?

Amb*_*ber 226

使用cursor.lastrowid得到插入光标对象的最后一行ID,或者connection.insert_id()从该连接上最后插入获取的ID.

  • @ xiaohan2012 2个进程如何使用相同的连接? (24认同)
  • `lastrowid`是否仅在当前交易提交后才可用? (4认同)
  • @ hienbt88他可能是线程,我已经这样做了,除非您正确利用线程安全性,否则它可能会引起问题。我亲自为每个线程实例化一个新的连接,这是一个可爱的解决方法,因为由于某种原因提交(实际上是自动提交)对我不起作用,由于许多并发线程都发出了一些查询,所以我进行了严重的交织每秒。 (4认同)
  • 如果两个进程使用相同的连接同时插入一行,该怎么办?`insert_id`将返回哪个id? (2认同)

And*_*rew 108

另外,cursor.lastrowid(MySQLdb支持的dbapi/PEP249扩展):

>>> 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,)
Run Code Online (Sandbox Code Playgroud)

cursor.lastrowidconnection.insert_id()比另一次MySQL往返要便宜一些,便宜得多.

  • 我刚遇到一个问题,`cursor.lastrowid`返回的内容与`connection.insert_id()`不同.`cursor.lastrowid`返回最后一个插入id,`connection.insert_id()`返回'0`.怎么可能? (5认同)
  • 为什么`cursor.lastrowid`比`connection.insert_id()`便宜? (4认同)
  • 只是因为cursor.lastrowid是作为cursor.execute()的一部分在游标对象上自动设置的,并且只是一个属性查找.connection.insert_id()是一个额外的不必要的函数调用 - 已经被调用并且其结果在lastrowid属性上可用. (3认同)

Hte*_*hno 32

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

id = cursor.lastrowid
Run Code Online (Sandbox Code Playgroud)

......也应该工作,显然是基于每个连接.


Kei*_*ith 6

SELECT @@IDENTITY AS 'Identity';
Run Code Online (Sandbox Code Playgroud)

要么

SELECT last_insert_id();
Run Code Online (Sandbox Code Playgroud)

  • [对于LAST_INSERT_ID(),最近生成的ID在每个连接的基础上在服务器中维护.它不会被其他客户更改.](http://dev.mysql.com/doc/refman/5.5/en/getting-unique-id.html) (7认同)
  • 这允许竞争条件,因为您从服务器请求最后一行id.因为我,你不要那么乱. (2认同)