Python mysqlプライマリ・キーidの取得


使用するmysql文は主に次のとおりです.
author_id = cursor.Lastrowid相等しい:author_id = conn.insert_id()
このような需要があり、データを挿入した後、返されたプライマリ・キーidを取得し、初めて取得することができ、2回目の挿入に失敗すると、プライマリ・キーidを取得できなくなる.実際には、
(一)需要:
例:
name,plat(プラットフォーム)を唯一のプライマリ・キーとし、
nameは異なるplatformで同じかもしれないので、異なるplatformのnameについては、同じplatformのnameで2回目の格納は行われません.
(二)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()