4
conn = MySQLdb.connect (host = "localhost", user="root", passwd="xxxx", db="xxxxx")
     cursor = conn.cursor()
     cursor.execute ("SELECT * FROM pin WHERE active=1")
     while (1):
       row = cursor.fetchone()
       st = str(row[2])
       pin = str(row[1])
       order = str(st)+str(pin)
       if row == None:
          break
       sendSerial(order)
conn.close()

Why st = str(row[2]) become error? How should retrieve rows from the database into a variable?

Thank You for your answer.

2
  • shouldn't the check if row == None: be before ` st = str(row[2])`?? Commented Mar 21, 2012 at 14:16
  • The check should be if row is None, not if row == None. Commented Mar 21, 2012 at 14:18

1 Answer 1

11

st = str(row[2]) is an error because cursor.fetchone() returns None when there are no more rows.

Fix it with one of these approaches:

row = cursor.fetchone()
while row:
    do_stuff()
    row = cursor.fetchone()

or

for row in cursor:
    do_stuff()

or

while True:
    row = cursor.fetchone()
    if row is None:  # better: if not row
          break
    do_stuff()
Sign up to request clarification or add additional context in comments.

1 Comment

do_stuff is nothing. It's just a way of saying "the rest of your code goes here".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.