【问题标题】:How do I get the "id" after INSERT into MySQL database with Python?如何在使用 Python 插入 MySQL 数据库后获取“id”?
【发布时间】: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”?

【问题讨论】:

标签: python mysql database


【解决方案1】:

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

【讨论】:

  • 如果两个进程使用相同的连接同时插入一行会怎样。 insert_id 会返回哪个 id?
  • @xiaohan2012 2个进程如何使用同一个连接?
  • lastrowid 是否仅在当前事务提交后可用?
  • @hienbt88 他可能是指线程,我已经这样做了,除非您正确利用线程安全,否则可能会导致问题。我亲自去为每个线程实例化一个新连接,这是一个可爱的解决方法,因为由于某种原因提交(实际上是自动提交)对我不起作用,由于许多并发线程都发出一些查询,我得到了一些严重的交织每秒。
  • 不适用于使用插入、选择和位置的重复记录。
【解决方案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 便宜得多。

【讨论】:

  • 为什么cursor.lastrowidconnection.insert_id() 便宜?
  • 只是因为 cursor.lastrowid 作为 cursor.execute() 的一部分自动设置在光标对象上,并且只是一个属性查找。 connection.insert_id() 是一个额外的不必要的函数调用 - 一个已经被调用并且其结果在 lastrowid 属性上可用。
  • 我刚刚遇到了一个问题,cursor.lastrowid 返回的内容与connection.insert_id() 不同。 cursor.lastrowid 返回最后一个插入 id,connection.insert_id() 返回 0。怎么可能?
  • @moose,可能并发进程正在使用相同的连接进行并行数据库插入。
  • @FlyingAtom,因为这是在 python2 而不是 python3 上运行的。
【解决方案3】:

Python DBAPI 规范还为游标对象定义了 'lastrowid' 属性,所以...

id = cursor.lastrowid

...也应该可以工作,而且它显然是基于每个连接的。

【讨论】:

    【解决方案4】:
    SELECT @@IDENTITY AS 'Identity';
    

    SELECT last_insert_id();
    

    【讨论】:

    【解决方案5】:

    这可能只是 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 值实际上是

    【讨论】:

    • @krzys_h 感谢您查看此 K,但您的编辑在我的测试中失败,因此我拒绝了您的编辑。如果您不介意也支持编辑?
    猜你喜欢
    • 2019-01-16
    • 2016-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-20
    • 2014-02-18
    • 1970-01-01
    相关资源
    最近更新 更多