zielperson
zielperson

Reputation: 3

Would like to just display 3 rows from mySQL result in python

So right now I have a query that returns about 20 rows. I do need these later

cur.execute(query)

for rows in cur.fetchall():
    print(rows)

cur.close()
conn.close()

How could I write the for loop to just write row in range 1-3?

Upvotes: 0

Views: 65

Answers (2)

Riad
Riad

Reputation: 3850

cur.execute(query)

var loop_count = 0 
for rows in cur.fetchall():
   if loop_count == 3:
     break 
   print(rows)
   loop_count = loop_count+1

cur.close()
conn.close()

Hope this helps.

Upvotes: 0

Glen Swinfield
Glen Swinfield

Reputation: 638

Use slice notation to get the first three items from rows. http://www.pythoncentral.io/how-to-slice-listsarrays-and-tuples-in-python/

for row in cur.fetchall()[:3]:
    print row

Upvotes: 3

Related Questions