Autocommit related issue

29 views
Skip to first unread message

Gaurav Jain

unread,
Jun 9, 2022, 1:20:37 PM6/9/22
to PyMySQL Users
I am using pymysql module. Below is the sample code I am using.
username_keys_list has 56 elements. Issue is during for loop, at 21th element, Alter statement fails.

The expected thing is if any of statement fails in this, whole transaction should be rolled back.
But instead of it, query is executing and persisting in DB for initial 20 elements. So, that means, for 20 elements, autocommit is running for first 20 elements despite that I explicitly mentioned autocommit=False when creating connection object.

So, for 20 elements, it is updating the password in Database while rest 36 are unchanged.
But I want that all passwords remain unchanged if any of query fails.

Sample code :


    db.begin()
    try:
        for x in username_keys_list:
            actual_db_username = secret_original_value[x]

            # generating random password
            updated_password_value = generate_random_password()

            sql_query = "ALTER USER '%s'@'' IDENTIFIED BY '%s';"%(actual_db_username, updated_password_value)
            cursor.execute(sql_query)
       
        db.commit()
        db.close()

    except Exception as e:
        db.rollback()
        print(e)
        db.close()
        sys.exit(1)
Reply all
Reply to author
Forward
0 new messages