3 回答

TA貢獻2003條經(jīng)驗 獲得超2個贊
另外,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往返便宜,而且便宜很多。

TA貢獻1795條經(jīng)驗 獲得超7個贊
Python DBAPI規(guī)范還為光標對象定義了“ lastrowid”屬性,因此...
id = cursor.lastrowid
...也應(yīng)該起作用,并且顯然基于每個連接。
添加回答
舉報