我正在尝试使用python向数据库添加一些数据。但是我无法获得最后插入的记录的自动增量primary_key
。
我的代码如下:
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()
然后转到insert_vehicle
函数。在该功能中,我想要:
vehicle
vehicle_price
表中添加新价格vehicles
表中最后插入的车辆主键函数insert_vehicle
如下:
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
insert_vehicle_price
如下所示:
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
有什么办法解决吗?
答案 0 :(得分:2)
如果您的primary_key是ID,则可以使用cursor.lastrowid
获取插入到光标对象上的最后一行ID,或使用connection.insert_id()
获取该连接上最后插入的ID。 / p>