Having trouble here, It worked when I had multiple (%s,%s) and data was (user,pass) or something like that.
However with the following code I keep getting this error.
query = query % tuple([db.literal(item) for item in args])
TypeError: not all arguments converted during string formatting
Why does this keep happening? It only occurs when there is only a single argument
This code is from my flask application
username = request.values['username']
update_stmt = (
"UPDATE ACCOUNTS SET IN_USE = 1 WHERE USER = '(%s)'"
)
data = (username)
cursor.execute(update_stmt,data)
asked Jan 11, 2017 at 12:23
k9b
1,4934 gold badges26 silver badges56 bronze badges
-
Is this sorted out now?e4c5– e4c52017年02月15日 23:38:22 +00:00Commented Feb 15, 2017 at 23:38
1 Answer 1
For a single valued tuple to be recognized as a tuple you need a trailing ,
data = (username,)
And unrelated, you don't really need to quote in your query
"UPDATE ACCOUNTS SET IN_USE = 1 WHERE USER = (%s)"
Your full code should be
username = request.values['username']
update_stmt = (
"UPDATE ACCOUNTS SET IN_USE = 1 WHERE USER = (%s)"
)
data = (username,)
cursor.execute(update_stmt,data)
answered Jan 11, 2017 at 12:25
e4c5
53.9k11 gold badges110 silver badges139 bronze badges
Sign up to request clarification or add additional context in comments.
7 Comments
k9b
Thanks! Are you sure I do not need the quotes? Its an email address with a @ in it that was throwing errors if not in quotes, either way I shall try :) Thanks again
e4c5
well, i have never used quotes in a prepared statement but your comment caused self doubt and I checked the docs :-) the examples here don't have quotes either: dev.mysql.com/doc/connector-python/en/…
k9b
Does this look simpler? Its giving me an error but for one value it seems more readable update_stmt = ("UPDATE ACCOUNTS SET IN_USE = 1 WHERE USER = '%s'" % username) cursor.execute(update_stmt)
k9b
Super similar error though :/ ValueError: need more than 1 value to unpack
e4c5
noooooo don't ever use % string formatting in sql that's unsafe.
|
default