【发布时间】:2021-09-15 03:53:29
【问题描述】:
我执行一个 INSERT INTO 语句
cursor.execute("INSERT INTO mytable(height) VALUES(%s)",(height))
我想得到主键。
我的表有 2 列:
id primary, auto increment
height this is the other column.
我刚刚插入后如何获得“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。
【讨论】:
insert_id 会返回哪个 id?
lastrowid 是否仅在当前事务提交后可用?
另外,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 便宜得多。
【讨论】:
cursor.lastrowid 比connection.insert_id() 便宜?
cursor.lastrowid 返回的内容与connection.insert_id() 不同。 cursor.lastrowid 返回最后一个插入 id,connection.insert_id() 返回 0。怎么可能?
Python DBAPI 规范还为游标对象定义了 'lastrowid' 属性,所以...
id = cursor.lastrowid
...也应该可以工作,而且它显然是基于每个连接的。
【讨论】:
SELECT @@IDENTITY AS 'Identity';
或
SELECT last_insert_id();
【讨论】:
select last_insert_id() 相比,您将从 Workbench 获得不同的值
这可能只是 Python 中 PyMySql 的要求,但我发现我必须命名我想要 ID 的确切表:
在:
cnx = pymysql.connect(host='host',
database='db',
user='user',
password='pass')
cursor = cnx.cursor()
update_batch = """insert into batch set type = "%s" , records = %i, started = NOW(); """
second_query = (update_batch % ( "Batch 1", 22 ))
cursor.execute(second_query)
cnx.commit()
batch_id = cursor.execute('select last_insert_id() from batch')
cursor.close()
batch_id
输出:
5
...或任何正确的 Batch_ID 值实际上是
【讨论】: