用到的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()
网友评论