Search code examples
pythonmysqlmysql-connector-python

mysql.connector select query with binary values


Using Python's mysql.connector, how can I select all records that match a tuple?

For example:

ids = (b'6TRsHMzWSrq0zeembo0Vbg',
       b'7Qoq53lKTk-RZOi830t3MA', 
       b'7ZGO9S3DTcGHjwrfpV0E0A')

And then the query would do something like:

query = SELECT first_name
        FROM users
        WHERE id = (ids)

Returning records for all users whose ID appears in the tuple


Solution

  • Try doing this

    query = "SELECT first_name FROM users WHERE id IN " + str(list(ids))
    cursor.execute(query)
    

    On second thoughts, the following should also work

    query = "SELECT first_name FROM users WHERE id IN " + str(ids)
    

    EDIT

    OP mentions in comments that the ids are binary data returned from a previous query. In which case, taking hint from this answer and using BINARY operator, the following query should work

    query = "SELECT first_name FROM users WHERE BINARY id IN " + str(ids) ;