How do you safely and efficiently get the row id after an insert with mysql using MySQLdb in python?

后端 未结 4 520
独厮守ぢ
独厮守ぢ 2020-12-14 03:22

I have a simple table in mysql with the following fields:

  • id -- Primary key, int, autoincrement
  • name -- varchar(50)
  • description -- varchar(25
相关标签:
4条回答
  • 2020-12-14 04:10

    You could also do a

    conn.insert_id

    0 讨论(0)
  • 2020-12-14 04:15

    I think it might be

    newID = db.insert_id()
    

    Edit by Original Poster

    Turns out, in the version of MySQLdb that I am using (1.2.2) You would do the following:

    conn = MySQLdb(host...)
    
    c = conn.cursor()
    c.execute("INSERT INTO...")
    newID = c.lastrowid
    

    I am leaving this as the correct answer, since it got me pointed in the right direction.

    0 讨论(0)
  • 2020-12-14 04:15

    I don't know if there's a MySQLdb specific API for this, but in general you can obtain the last inserted id by SELECTing LAST_INSERT_ID()

    It is on a per-connection basis, so you don't risk race conditions if some other client performs an insert as well.

    0 讨论(0)
  • 2020-12-14 04:18

    The easiest way of all is to wrap your insert with a select count query into a single stored procedure and call that in your code. You would pass in the parameters needed to the stored procedure and it would then select your row count.

    0 讨论(0)
提交回复
热议问题