I'm totally new and learning Python+MySQL, And I have an issue with passing over 10 to %s
@app.route('/usr/<id>', methods=['GET'])
def selected_logs(id):
response_object = {'status': 'success'}
cur = mysql.connection.cursor()
cur.execute('''
SELECT
usr.id,
usr.corp_id,
date_format (log.date, '%%m/%%d/%%Y') AS date
FROM
(usr
INNER JOIN corps ON corps.id = usr.corp_id)
WHERE
usr.corp_id = %s
ORDER BY usr.id DESC;
''', (id))
results = cur.fetchall()
response_object['usr'] = results
return jsonify(response_object)
In the URL http://localhost:5000/usr/9 works, but start to 10... won't work, please help me.
MySQLdb._exceptions.ProgrammingError: not all arguments converted during bytes formatting
THANK YOU SO MUCH
Execute()takes an iterable as the second argument. You need to pass an iterable of values to bind to parameters,(id)is not an iterable. It is a common mistake to think that it is atuplebut it is not,(id,)is atuplewhich is an iterable.The error hides this issue because the
idvalue is'10'andstrS are iterables in Python.Edit: Response to comment
Execute()takes an iterable of values to bind to parameters in the query, and it must be an iterable in order forexecute()to support multiple parameters in the query. The only way(id)can be an iterable is ifiditself is an iterable.The parentheses don't construct a
tuple, the comma does. Even if you try to create atupleof one element using the explicit,tuple()constructor, you'll get an error without the comma.So why did
(id)work forid='9' but notid='10'? It's because in each caseidis a path variable which is astrby default and therefore(id)is astr. SincestrS are iterable,execute()unpacked(id)and tried to map it onto the parameters in the query. Since there is only one parameter in the query, the unpacking succeeds for every value ofidwith length=1. Whenid='10', it unpacks as'1','0'andexecute()tries to map it onto two parameters. But, since there's only one parameter, raises an exception:I'll agree that this message isn't very descriptive of the root cause here. There may have been more information in the complete stacktrace. Regardless, the important part is "not all arguments converted." It's telling you that there are more values than parameters in the query.