Search code examples
mysqlpython-3.xdjangodatabase-cursor

Python - Get result of an update query (Mysql) when performing raw SQL


I work on a Django project and need to apply changes in an other remote DB (not Django DB).

Those changes are async and launched with Celery. But when performing these queries, I need to know if updates are well done with counting affected rows, otherwise I must take corrective action. Until now, I haven't found any way to do this. I tried with cusr.fetchone() and curs.fetchall() but results are None. When I print(curs.execute()), the result is 0 even if the product is found. This thread says it should be 1 if update is done. Even the official documentation doesn't talk about this.

So, for the time, the only workaround I found is performing a first SELECT query and if rowcount < 1, I raise an Exception. Not really nice ...

Is there a way to do it better ? Nota : I use django.db.backends.mysql and pymysql


Solution

  • If not your approach, I will suggest you to check the affected rows right after your commit and check.

    from django.db import connection
    
    # Initialize affected_rows outside the context manager
    affected_rows = None
    
    # Assuming you have a SQL update query
    update_query = "UPDATE your_table SET your_column = your_value WHERE your_condition"
    
    # Get a cursor
    with connection.cursor() as cursor:
        # Execute the update query
        cursor.execute(update_query)
        
        # Commit the transaction
        cursor.connection.commit()
        
        # Get the number of affected rows
        affected_rows = cursor.rowcount
    
    # Check if the update was successful
    if affected_rows is not None and affected_rows > 0:
        # Update was successful, take appropriate action
        pass
    else:
        # No rows were affected, handle the error or raise an Exception
        raise Exception("No rows were affected by the update query.")
    

    Try this in sequence and find the affected rows

    1. Use the cursor.execute() method to execute the SQL query.
    2. Use the cursor.connection.commit() method to commit the transaction.
    3. Use the cursor.rowcount attribute to get the number of affected rows.