pythonpymysql

How to search results of PyMySQL query with IN operator when it returns a tuple of tuples?


I have a MySQL database table of ipv4 addresses I want to search against, I pull it in to a Python using an SQL query (PyMySQL library) with a single column in the SELECT and cursor.fetchall() but when I loop through the resulting tuple.

with conn.cursor() as cur:
    sqlQuery = 'SELECT ipv4_address FROM bad_ips WHERE IS NOT NULL'
    cur.execute(sqlQuery)
    bad_ips  = cur.fetchall() 
conn.close()

When I loop through it, it appears to return a tuple of tuples, show this sort of thing:

('192.168.1.1',) ('192.168.1.5',)

I want it to return just the IP addresses as expected like this:

'192.168.1.1' '192.168.1.5'

That way I can look up an IP using:

if str(this_ip_address) in bad_ips:

Solution

  • You can unwrap the first element of the tuples into a list doing something like this:

    bad_ip_list = [x[0] for x in bad_ips]

    and then iterate through the bad_ip_list.