Jake DeVries
Jake DeVries

Reputation: 327

Select Array from MySQL in Python without For Loop

I am trying to select an array of values from my MySQL without using a for loop. The for loop takes to long and I want to grab all of the values at once. I do not know what is wrong with my arguments and I am having a hard time interpreting what the error message I receive means.

zipcode = ["37204", "60964", "60068"]
connection = MySQLdb.connect(host="localhost", user="root", passwd="password", db="database", cursorclass=MySQLdb.cursors.SSCursor)
cursor = connection.cursor()  
query = "SELECT fips FROM us WHERE zip = %s"
cursor.executemany(query,zipcode)
results = cursor.fetchall()

The error looks like this:

query = query % tuple([db.literal(item) for item in args])
TypeError: not all arguments converted during string formatting

Any help is appreciated.

Upvotes: 1

Views: 1521

Answers (1)

Derek
Derek

Reputation: 1196

Python is not my forte and I've not used executemany before, but I don't think it's supposed to be used for executing code that's supposed to return something. You probably want to use IN with your query.

query = "SELECT fips FROM us WHERE zip IN ('%s')" % "','".join(zipcode)
cursor.execute(query)
results = cursor.fetchall()

Upvotes: 1

Related Questions