Var*_*nka 0 python mysql-python
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()
Run Code Online (Sandbox Code Playgroud)
为什么st = str(row [2])变成错误?应该如何从数据库中将行检索到变量中?
谢谢您的回答。
st = str(row[2])错误是因为没有更多行时cursor.fetchone()返回None。
使用以下方法之一修复它:
row = cursor.fetchone()
while row:
do_stuff()
row = cursor.fetchone()
Run Code Online (Sandbox Code Playgroud)
要么
for row in cursor:
do_stuff()
Run Code Online (Sandbox Code Playgroud)
要么
while True:
row = cursor.fetchone()
if row is None: # better: if not row
break
do_stuff()
Run Code Online (Sandbox Code Playgroud)