Python Mysql TypeError:'NoneType'对象不可订阅

时间:2012-03-21 14:13:57

标签: 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()

为什么st = str(row [2])会出错? 应该如何从数据库中检索行变量?

感谢您的回答。

1 个答案:

答案 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()
相关问题