Python中使用pymysql插入数据后如何获取自增ID并赋值给tp_id?

pymysql 操作 直接插入数据库

xxx.py 文件里

sql = 'INSERT INTO xxx (a_id, title, body) VALUES (%s, %s, %s)'

value = (tttt, tttt, tttt,)

conn.execute(sql, value)

这一句如果想得到 面上面插入数据的 ID

用下面三句

tp_id =conn.execute(‘select LAST_INSERT_ID();’)
tp_id = conn.execute(‘select max(id) from xxx;’)
tp_id = conn.execute(‘select @@identity’)

上面三个语句 都是返回 执行成功的行数 也就是说 tp_id 的结果是 1 或者 0

那有什么办法 得到该记录的 id 并赋值给 tp_id ?
用 conn.lastrowid 可以。
但是不知道用 上面三条语句中的方法怎么得出这个 ID 并赋值给 tp_id ?

谢谢
Python中使用pymysql插入数据后如何获取自增ID并赋值给tp_id?


8 回复

自增 ID 不好处理,如果是非自增 ID,插入记录之前记录下来就好了。


在pymysql里,插入数据后想拿到自增ID,直接用cursor.lastrowid就行。这玩意儿在你执行INSERT语句后,会返回最后插入行的自增ID值。

下面是个完整例子:

import pymysql

# 连接数据库
connection = pymysql.connect(
    host='localhost',
    user='your_username',
    password='your_password',
    database='your_database'
)

try:
    with connection.cursor() as cursor:
        # 执行插入语句
        sql = "INSERT INTO your_table (name, email) VALUES (%s, %s)"
        cursor.execute(sql, ('张三', 'zhangsan@example.com'))
        
        # 获取自增ID
        tp_id = cursor.lastrowid
        print(f"插入成功,自增ID为: {tp_id}")
        
    # 提交事务
    connection.commit()
finally:
    connection.close()

关键就这一行:tp_id = cursor.lastrowid。执行完INSERT后马上调用,tp_id就拿到自增ID了。

注意两点:1)确保表里确实有自增主键;2)这个方法只对单条插入有效,批量插入得用别的方式。

简单说就是:插入完直接cursor.lastrowid拿ID。

conn.insert_id() 这个试试

result_proxy = self.execute(sql, args)
id = result_proxy.lastrowid

直接用 cursor.lastrowid 就行了

你后面写的那三个,不都是对数据库做查询么,直接解析查询结果就好了啊


现在就是直接用的 tp_id = cursor.lastrowid

第一个 insert into xxxx 后

第二个 现在可以用: 'INSERT INTO aaa (a_id, body) VALUES (LAST_INSERT_ID(), ‘bbbbbb’)'

但是我后面还想再跟 一个 'INSERT INTO bbb (b_id, body) 这个 b_id 也是用的第一个 insert into xxxx 后的记录 id

但是第三个再用 LAST_INSERT_ID() 的话,得到的就是第二个 插入表的 记录 id 了

说的有点混乱。
实在不行就暂时先用 tp_id = cursor.lastrowid 这个吧

我觉得你这样过于复杂了吧, 非得这样的话,就需要先查出来,定义一个变量保存呗

回到顶部