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.
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往返要便宜一些,便宜得多.
Hte*_*hno 32
Python DBAPI规范还定义了游标对象的'lastrowid'属性,所以......
id = cursor.lastrowid
Run Code Online (Sandbox Code Playgroud)
......也应该工作,显然是基于每个连接.
SELECT @@IDENTITY AS 'Identity';
Run Code Online (Sandbox Code Playgroud)
要么
SELECT last_insert_id();
Run Code Online (Sandbox Code Playgroud)