Sandeepan Nath
Sandeepan Nath

Reputation: 10284

How to iterate through cursor after mysql select * query in python?

I am querying all the fields of a mysql table like this -

query = """select * from %s where %s=%s;""" % (tableName,key,value)
cursor.execute(query)

Now, I would like to iterate over the results. I do not want to specify the column names which I would like to fetch as I would like to fetch all. This is part of a generic migration verification script which is supposed to do the verification for all the mysql tables. Since there will be different number of columns in different tables, I would like a general solution.

I checked https://stackoverflow.com/a/25347195/351903 but it involves specific fields.

Upvotes: 0

Views: 606

Answers (2)

Siegmeyer
Siegmeyer

Reputation: 4512

MySQLdb conforms to PEP-249.

Therefore,execute must return an iterator. You can just do:

for tupl in cursor.execute(query):
    pass

where tupl is a tuple.


*Alternatively, you can use fetchone, fetchmany(n) or fetchall() to evaluate at once.

Upvotes: 2

Deepak Kumar
Deepak Kumar

Reputation: 668

First run below query

sp_help Table

then get the column names from that

after that run your code. Because you will have column names.

I also created this type of utility. That was windows console app.

Upvotes: 0

Related Questions