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()
为什么st = str(row [2])会出错? 应该如何从数据库中检索行变量?
感谢您的回答。
答案 0 :(得分:4)
st = str(row[2])
是一个错误,因为当没有更多行时,cursor.fetchone()
会返回None
。
使用以下方法之一修复它:
row = cursor.fetchone()
while row:
do_stuff()
row = cursor.fetchone()
或
for row in cursor:
do_stuff()
或
while True:
row = cursor.fetchone()
if row is None: # better: if not row
break
do_stuff()