Python variables in SQL Update query

Viewed 7499

I'm very new to Python and I'm facing a problem with Python-SQLite connection.

con=connection()
cur=con.cursor()
cur.execute("""UPDATE table1 SET column1=%s WHERE column2=%d""",(var1,var2))
if(cur.rowcount > 1):
    cur.commit()
else:
    return["Error"]

Where var1 stores a string, and var2 stores an integer.

The error is the following:

SQLError('SQLError: near "%": syntax error',)

I've read plenty of tutorials and threads in here about how to write my query with the variables and I'm in a dead end.

2 Answers

This worked for me

mycursor.execute("UPDATE table SET column WHERE name = '%s' AND age = %s" % ("Alex", 30) 

When passing in a string.

Use quotes

And at the end of the execute statement, use

%

Keep in mind that if you will pass multiple variables you have to put them inside a tuple

Took me a long time just to understand that you have to have the % at the end when writing an UPDATE query

Related