【发布时间】:2018-12-11 15:28:27
【问题描述】:
我正在尝试使用 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
知道怎么解决吗?
【问题讨论】:
-
如果我是你,我可能已经使用 SQLAlchemy ORM 完成了这篇文章
-
请在mysql客户端运行
SHOW CREATE TABLE vehicles,并将结果包含在您的问题中。确认该表实际上有一个自增的PK,以及它是哪一列。 -
@BillKarwin 我收到一个错误
ERROR: syntax error at or near "CREATE" LINE 1: SHOW CREATE TABLE vehicles ^ SQL state: 42601 Character: 6 -
您的问题被标记为mysql。但该错误格式表明您使用的是 PostgreSQL,而不是 MySQL。这可以解释为什么
lastrowid的行为不像您认为的那样。 -
确实如此。知道如何用 postgresql 做到这一点吗?