Forums

how to update mysql row using user information

[edited by admin: formatting]

name='emmanuel'
age=30
country='us'
id=100

cur.execute( UPDATE table SET user_name=name, age=age, country=country WHERE user_id= id)

how do you update a table using the above variables in python. i have search the web but was unable to find an example.

thanks

Are you using Django?

cur.execute takes a string. You could use string formatting to put in the variables.

no i am using bottle

please ignore conrad's terrible advice. he was tired yesterday. using string formatting in sql statements is a terrible idea because it opens you up to SQL injection attacks.

instead, you should replace your values with a placeholder character "?", and then pass your parameters to cur.execute as a second argument, in a tuple, like this:

cur.execute(
    "UPDATE table SET user_name=?, age=?, country=? WHERE user_id=?)",
    (name, age, country, id)
)

More info here: https://docs.python.org/3.5/library/sqlite3.html.

If you're using mysql or postgres instead of sqlite, they may use a different placeholder character instead of the "?"

I just read the thread title! If you're using MySQL, the placeholder is "%s", so:

cur.execute(
    "UPDATE table SET user_name=%s, age=%s, country=%s WHERE user_id=%s)",
    (name, age, country, id)
)