I am currently in the process of learning how to use the sqlite3 module inside Python. I'm trying to write code that will update a value from a column in sqlite by adding a new value to an existing value, but I'm running into formatting issues that I don't know how to fix...
I know that the basic syntax for doing this (as far as I'm aware) is the following:
sql_statement = "UPDATE table
SET column_name = column_name + new_value
WHERE condition;"
The issue I'm running into is that I'm trying to insert the column name using dictionary parameters from python. This is where the problem is occuring in my code:
muscle = 'Lats'
num_sets = 5
week_num = 40
sql_statement = f"UPDATE WeeklyMuscleSets
SET {muscle} = (:muscle) + (:num_sets)
WHERE WeekID = (:week_num);"
parameters = {'muscle':muscle,'num_sets':num_sets,'week_num':week_num}
c.execute(sql_statement,parameters)
The code runs just fine, but instead of adding to the existing value in the table it is replacing it. I did some testing, and when I manually enter the value for the "muscle" variable, it updates just fine.
muscle = 'Lats'
num_sets = 5
week_num = 40
sql_statement = f"UPDATE WeeklyMuscleSets
SET {muscle} = Lats + (:num_sets)
WHERE WeekID = (:week_num);"
parameters = {'num_sets':num_sets,'week_num':week_num}
c.execute(sql_statement,parameters)
It also worked when I used f-string formatting for the muscle variable, however I know that is bad practice and leaves the code vulnerable to injection attacks.
For some reason when I use the parameters it doesn't add the new value to the existing one and instead replaces it, and I'm at a loss as to why. Any help with this is greatly appreciated!