[英]How to get primary_key of last inserted record in database with Python
I'm trying to add some data to database using python. 我正在尝试使用python向数据库添加一些数据。 But I'm unable to get the auto increment
primary_key
of the last inserted record. 但是我无法获取最后插入的记录的自动增量
primary_key
。
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. 然后转到
insert_vehicle
函数。 In that function I want: 在该功能中,我想要:
vehicle
to the database vehicle
vehicle_price
table vehicle_price
表中添加新价格 vehicles
table vehicles
表中最后插入的车辆主键 The function insert_vehicle
is as follows: 函数
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
And insert_vehicle_price
looks as follows: 而
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
Any idea how to solve it? 知道如何解决吗?
如果您的primary_key是ID,则可以使用cursor.lastrowid
获取插入在光标对象上的最后一行ID,或使用connection.insert_id()
从该连接的最后一次插入获取ID。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.