Python mysql获取主键id

本文介绍了一种在Python中使用MySQL时确保数据唯一性的方法。通过查询、更新及插入操作,结合具体实例展示了如何避免重复数据并正确获取最后一次插入记录的主键ID。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

用到的mysql语句主要为:

author_id = cursor.lastrowid
相等于 : author_id = conn.insert_id()

有这么一段需求,插入数据后,获取返回的主键id,首次可以获取到,第二次插入失败,就获取不到主键id了。其实我们可以这样实现:

(一)需求:

例子:

我们将name , plat(平台)为唯一主键,

因为name 在不同platform上可能相同,所以对于不同platform的name,我们都要将name存进去,是同一platform的name 就不再进行第二次存入

(二)Python代码实现:

# 1 先进行查询是否存在
# 2 再进行更新操作(其实这一步可以不用的)
# 3 对数据进行插入

author_id = None
## (一)insert into mysql
try:
    # 查重处理
    self.cursor.execute("""select author_id from tb_author where name = %s and platform = %s """,
                   [item['name'], item['platform']])
    # 是否有重复数据
    repetition = self.cursor.fetchone()
    # 重复
    if repetition:
        if len(repetition) > 0:
            author_id = repetition[0]
    else:
        # 更新
        result_code = self.cursor.execute(
            "UPDATE  tb_author set avatar=%s,type=%s,fans_count=%s,scan_count=%s,collect_count=%s,is_delete=%s where tb_author.name = %s and tb_author.platform = %s",
            [item['avatar'], item['type'], item['fans_count'], item['scan_count'], item['collect_count'],
             item['is_delete'], item['name'], item['platform']])
        # 第一次插入
        if not result_code:
            self.cursor.execute(
                "insert into tb_author (name,platform,avatar,type,fans_count,scan_count,collect_count,is_delete,gmt_create,gmt_modified) values(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)",
                (item['name'], item['platform'], item['avatar'], item['type'], item['fans_count'],
                 item['scan_count'], item['collect_count'], item['is_delete'], item['gmt_create'],
                 item['gmt_modified']))
            author_id = self.cursor.lastrowid
    print('author_id ==== > ',author_id)
except Exception as e:
    print('inser mysql error ---> ',e)
self.conn.commit()
self.cursor.close()
self.conn.close()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值