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
vehicleto the database - to add a new price in
vehicle_pricetable - for previous step I need the last inserted vehicle primary key from
vehiclestable
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?
SHOW CREATE TABLE vehiclesin 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.ERROR: syntax error at or near "CREATE" LINE 1: SHOW CREATE TABLE vehicles ^ SQL state: 42601 Character: 6lastrowiddoesn't behave as you think it should.