Python mysql獲取主鍵id
阿新 • • 發佈:2019-02-09
用到的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()