如何在使用Python INSERT到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”?
 使用cursor.lastrowid获取游标对象上插入的最后一个行ID,或者使用connection.insert_id()从该连接的最后一个插入中获取ID。 
 另外, 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.lastrowid比connection.insert_id()要便宜一些,比另一次往返MySQL要便宜得多。 
Python DBAPI规范还定义了游标对象的“lastrowid”属性,所以…
 id = cursor.lastrowid 
…也应该工作,这显然是每个连接的基础。
 SELECT @@IDENTITY AS 'Identity'; 
要么
 SELECT last_insert_id();