0

My list is as follows:

['1.0.176.20:14386', '1.0.179.115:20208', '1.0.218.241:14699', '1.0.242.3:27376', '1.1.218.165:24513']

from:

sessions = [session[0].replace("'", '"') for session in sessions]

But in mysql:

cur.execute("""
        SELECT *
        FROM logs
        WHERE logs.session IN %s
        """, (
            sessions,
        ))

it returns nothing because of query being:

SELECT *
        FROM logs
        WHERE logs.session IN ("'1.0.176.20:14386'", "'1.0.179.115:20208'")

How do I fix this in mysql/list?

1 Answer 1

1

When you format that string what you will get is

... WHERE logs.session IN ['1.0.176.20:14386', '1.0.179.115:20208', (...)]

because that is the string representation of a list ([...]).

You need to do something like this:

sessions_in = ",".join(map(lambda x: "'{0}'".format(x), sessions))
cur.execute("""
    SELECT *
    FROM logs
    WHERE logs.session IN ( {0} )
    """.format(sessions_in))

It will create a string by joining all the list items with a , between them. As this would only create a single string with all the elements inside it ("1,2,3,(...)"), you need to transform each string into a quoted string before joining them. That's what that map will do, giving you:

"'1.0.176.20:14386','1.0.179.115:20208','1.0.218.241:14699','1.0.242.3:27376','1.1.218.165:24513'"
Sign up to request clarification or add additional context in comments.

1 Comment

Can you perhaps elaborate a bit more?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.