问题:使用Python插入MySQL数据库后,如何获得“ id”?

我执行INSERT INTO语句

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

我想获取主键。

我的表有2列:

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

我刚插入这个后,如何获得“ id”?

I execute an INSERT INTO statement

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

and I want to get the primary key.

My table has 2 columns:

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

How do I get the “id”, after I just inserted this?


回答 0

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

Use cursor.lastrowid to get the last row ID inserted on the cursor object, or connection.insert_id() to get the ID from the last insert on that connection.


回答 1

另外,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,)

cursor.lastrowidconnection.insert_id()比另一次MySQL往返便宜,而且便宜很多。

Also, cursor.lastrowid (a dbapi/PEP249 extension supported by 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 is somewhat cheaper than connection.insert_id() and much cheaper than another round trip to MySQL.


回答 2

Python DBAPI规范还为光标对象定义了“ lastrowid”属性,因此…

id = cursor.lastrowid

…也应该起作用,并且显然基于每个连接。

Python DBAPI spec also define ‘lastrowid’ attribute for cursor object, so…

id = cursor.lastrowid

…should work too, and it’s per-connection based obviously.


回答 3

SELECT @@IDENTITY AS 'Identity';

要么

SELECT last_insert_id();
SELECT @@IDENTITY AS 'Identity';

or

SELECT last_insert_id();

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。