【问题标题】:How to get primary_key of last inserted record in database with Python如何使用Python获取数据库中最后插入记录的primary_key
【发布时间】:2018-12-11 15:28:27
【问题描述】:

我正在尝试使用 python 将一些数据添加到数据库中。但我无法获得最后插入记录的自动增量primary_key

我检查了herehere 的类似问题,但没有奏效。

我的代码如下:

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 做到这一点吗?

标签: python mysql


【解决方案1】:

如果您的 primary_key 是 ID,那么您可以使用 cursor.lastrowid 获取插入游标对象的最后一行 ID,或使用 connection.insert_id() 获取该连接上最后插入的 ID。

【讨论】:

    猜你喜欢
    • 2015-01-29
    • 2011-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-14
    相关资源
    最近更新 更多