python - 如何使用 Python 获取数据库中最后插入记录的主键

标签 python mysql

我正在尝试使用 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_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

知道怎么解决吗?

最佳答案

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

关于python - 如何使用 Python 获取数据库中最后插入记录的主键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51152490/

相关文章:

Python - Selenium(通过 CSS 选择器查找元素)

Python-如何为字典中的值设置最大数量?

Python 字典值检查不为空且不为空

通过 multiprocessing.pool 的 Python3 并行代码比顺序代码慢

php - 在数据库中上传 csv 文件,但最后一个字段添加一个空白数据

mysql - 从所有行中查找并替换 '000L'

python - 设置模块不推荐使用的警告

mysql - 从 double 据类型转换为十进制

php - 是否可以在codeigniter中连接两个dbms MySQL和postgresQL?

javascript - 如何使用jquery在数据库中创建表