Python loop example

I need an example of python code that does the following

execute the query "select id, col1, col2 from tab1"
Then Iterate through the query results
 
Thanks
cpeters5Asked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

plusone3055Commented:
c.execute(select id, col1, col2 from tab1)
print c.fetchall()


or 


c.execute(select id, col1, col2 from tab1)
for i in range(c.rowcount): 
row = c.fetchall()
print row

Open in new window

cpeters5Author Commented:
Thanks plusone3055
Would you please expand a little?  Within th eloop, I want to do one thing with col1 and another with col2.
cpeters5Author Commented:
I want to see explicit syntax for getting individual elements off row.
say, printing col1 and col2 in two separate print statements.

Sorry, a newbie.
Thanks
gelonidaCommented:
@plusone3055
The second part of your answer seems to have a small error.

The for loop as no indented lines following it and
row =  c.fetchall()

Open in new window

should probably be
rows =  c.fetchall()

Open in new window



To do something with individual columns of a row:

c.execute(select id, col1, col2 from tab1)
for row in  c.fetchall():
    id_, col1, col2 = row
    # do something with col1 and or col2

Open in new window


Alternatively:
c.execute(select id, col1, col2 from tab1)
for row in  c.fetchall():
    col1 = row[1]
    col2 = row[2]
    # do something with col1 and or col2

Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Python

From novice to tech pro — start learning today.