user3364161
user3364161

Reputation: 375

pyodbc UPDATE throws an exception

I'm making a python program that does Elo calculations for an Azure SQL database. The problem is with the last two 'cursor.execute' commands (the UPDATEs).

I took out part of the code before posting here to make it smaller, but all the variables are properly passed from the find_winner and find_loser methods-- the print commands show the right value.

When I run the program as is, it prints the change in ratings and the message from the except block. When I comment out the UPDATE methods, it doesn't print the except message. The only reason I can come up with is that the variables from the tuple from find_winner and find_loser aren't being entered into the SQL statement properly.

I tried running it with ? and '%s' instead of winner_new_rating and winner_id, but none of the 3 versions worked.

Is there something obvious I'm missing? What's the proper way of entering parameters stored in variables?

def rate():
    try:
        (winner_rating,winner_name,winner_id) = find_winner()
        (loser_rating,loser_name,loser_id) = find_loser()

        cursor = conn.cursor()

        print(winner_name, "wins", winner_rating, "-->", winner_new_rating)
        print(loser_name, "loses:", loser_rating, "-->", loser_new_rating)

        cursor.execute("UPDATE KIDS SET Rating = winner_new_rating WHERE LocalID = winner_id")
        cursor.execute("UPDATE KIDS SET Rating = loser_new_rating WHERE LocalID = loser_id")

        conn.commit()

    except:
        print("Rate method error")

Upvotes: 1

Views: 287

Answers (1)

user325117
user325117

Reputation:

This is the correct syntax:

try:
    cursor.execute("UPDATE KIDS SET Rating = ? WHERE LocalID = ?", 
        str(winner_new_rating), winner_id)
    cursor.execute("UPDATE KIDS SET Rating = ? WHERE LocalID = ?",
        str(loser_new_rating), loser_id)
except DatabaseError as e:
    print(str(e))

Upvotes: 3

Related Questions