Boky
Boky

Reputation: 12054

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:

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?

Upvotes: 0

Views: 4493

Answers (1)

hondvryer
hondvryer

Reputation: 442

In case your primary_key is the ID then you can use cursor.lastrowid to get the last row ID inserted on the cursor object, or connection.insert_id() to get the ID from the last insert on that connection.

Upvotes: 3

Related Questions