[Python] Mysql rowcount always returns 1 on INSERT IGNORE statement

Discussão em 'Python' iniciado por Stack, Fevereiro 14, 2025.

  1. Stack

    Stack Membro Participativo

    I am using pymysql connector to do some inserts into my database. I am trying to return whether or not a record was added or updated.

    My code is

    import pymysql
    db = pymysql.connect(host='127.0.0.1',user='USERNAME',password='PASSWORD',database='DATABASE')
    cursor = db.cursor()

    sql = "INSERT IGNORE INTO `Table` (key, via) SELECT temp.`id`, 'Via_Bot' FROM (SELECT %s AS id) temp LEFT JOIN `Other_Table` ON `Other_Table`.id = temp.id WHERE `Other_Table`.id IS NULL;"
    key_id = 'ab12cd'
    rows = cursor.execute(sql, (key_id,))

    db.commit()


    In this situation rows and cursor.rowcount always returns 1 even if a record was not inserted/modified. How do I correctly see if a record has been updated/inserted?

    Continue reading...

Compartilhe esta Página