简体   繁体   中英

How to get primary_key of last inserted record in database with Python

I'm trying to add some data to database using python. But I'm unable to get the auto increment primary_key of the last inserted record.

I've checked similar questions here and here , but it haven't worked.

My code is as follows:

def insert_vehicles_to_db(vehicle):
    conn = db_connection()
    cur = conn.cursor()    

    if vehicle_not_exists(vehicle, conn, cur):
        try:
            insert_vehicle(vehicle, conn, cur)
        except Exception as e:
            pass    
    else:
        pass
    conn.close()

Then it goes to insert_vehicle function. In that function I want:

  • to add a new vehicle to the database
  • to add a new price in vehicle_price table
  • for previous step I need the last inserted vehicle primary key from vehicles table

The function insert_vehicle is as follows:

def insert_vehicle(vehicle, conn, cur):
    try:
        query = "INSERT INTO vehicles (reference, data, price, reference_url, timestamp) VALUES (%s, %s, %s, %s, %s);"
        cur.execute(query, (vehicle['reference'], "", vehicle['price'], vehicle['reference_url'], datetime.datetime.now()))


        ////////// I tried here vehicle_id = cur.lastrowid, it gives me always 0 //////////


        insert_vehicle_price(vehicle['price'], vehicle_id, conn, cur)
        conn.commit()

    except Exception as e:
        # TODO Handle error
        pass

And insert_vehicle_price looks as follows:

def insert_vehicle_price(price, vehicle_id, conn, cur):
    //// Here I need the correct vehicle_id to be able to insert a new record in `vehicle_price` table
    pass

Any idea how to solve it?

如果您的primary_key是ID,则可以使用cursor.lastrowid获取插入在光标对象上的最后一行ID,或使用connection.insert_id()从该连接的最后一次插入获取ID。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM