Python Mysql TypeError:“NoneType”对象不是subscriptab

2024-04-18 02:08:30 发布

您现在位置: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()

为什么st=str(行[2])变成错误? 如何将数据库中的行检索到变量中?

谢谢你的回答。


Tags: localhosthostconnectpinorderrootconncursor
1条回答
网友
1楼 · 发布于 2024-04-18 02:08:30

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()

相关问题 更多 >