0

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?

Boky
  • 11,554
  • 28
  • 93
  • 163
  • if I were you I've probably finished writing this using SQLAlchemy ORM – Azat Ibrakov Jul 03 '18 at 11:13
  • Please run `SHOW CREATE TABLE vehicles` in the mysql client, and include the result in your question. To confirm that the table actually has an auto-increment PK, and which column is it. – Bill Karwin Jul 03 '18 at 13:21
  • @BillKarwin I get an error `ERROR: syntax error at or near "CREATE" LINE 1: SHOW CREATE TABLE vehicles ^ SQL state: 42601 Character: 6` – Boky Jul 03 '18 at 13:30
  • Your question is tagged [tag:mysql]. But that error format indicates you are using PostgreSQL, not MySQL. That could explain why the `lastrowid` doesn't behave as you think it should. – Bill Karwin Jul 03 '18 at 13:35
  • That is true. Any idea how to do it with postgresql? – Boky Jul 03 '18 at 13:37
  • Possible duplicate of https://stackoverflow.com/questions/2944297/postgresql-function-for-last-inserted-id or https://stackoverflow.com/questions/5247685/python-postgres-psycopg2-getting-id-of-row-just-inserted – Bill Karwin Jul 03 '18 at 13:45

1 Answers1

3

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.

hondvryer
  • 442
  • 1
  • 3
  • 18