[Answered ]-Python โ€“ Get result of an update query (Mysql) when performing raw SQL

1๐Ÿ‘

โœ…

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.
๐Ÿ‘คPrudhviraj

Leave a comment