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

前端 未结 1 1282
别跟我提以往
别跟我提以往 2020-12-20 16:20

Status Quo:

I have a working database with tables and can query, insert, update, etc. Also the cursor is connected to the right database.

The table:

<
相关标签:
1条回答
  • 2020-12-20 16:48

    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,))
    
    0 讨论(0)
提交回复
热议问题