MySql cursors.execute() with only one parameter: Why is a string sliced into a list?

这一生的挚爱 提交于 2019-11-29 14:04:59

The problem is that ('hello') is a string and ('hello',) is a tuple. You need to always pass a tuple (or other such collection, like a list) as the values for your placeholders. The reason is that your placeholders are positional in your query, so the arguments should also have some order - and tuples and lists are two ways to get an ordered selection of objects.

Since its expecting a tuple or other collection, 106 gets converted to [1, 0, 6]. If you pass in (106,), it will be interpreted correctly.

Behind the scenes, this is what is going on:

>>> for i in '106':
...     print(i)
...
1
0
6
>>> for i in ('106',):
...    print(i)
...
106

So, your 'hack' is actually the correct solution, you just don't need the extra variable:

q = 'SELECT Last_Request_Time FROM Products WHERE idProduct = %s'
cursor.execute(q, (idProduct,))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!