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.
asked Jun 3, 2014 at 19:09
Jake DeVries
3273 silver badges14 bronze badges
-
In the declaration of the zipcode list, your comma is inside the first element. Is that a typo in the question or in your code?Derek– Derek2014年06月03日 19:27:05 +00:00Commented Jun 3, 2014 at 19:27
1 Answer 1
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()
answered Jun 3, 2014 at 19:37
Derek
1,1961 gold badge12 silver badges33 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
Alejo Dev
I don't think this is safe, but if you have your inputs controlled somewhere else this should work
default