2016-11-05 76 views
0

我試圖從MySQL表中檢索數據。TypeError:'long'對象沒有屬性'__getitem__'for MySQL

我的代碼

def getData(self, ID): 
    #Load data from MySQL 
query = 'SELECT * FROM goals WHERE ID = "%s"'% (ID) 
     try : 
      cursor.execute(query) 
      data = cursor.fetchone() 
      conn.commit() 
     except Exception as e: 
      raise e 
      data = False 

     if data is not False: 
      for row in data: 
       self.ID = row[0] 
       self.description = row[1] 
       self.imageID = row[2] 
       self.imageLink = row[3] 
       self.Location = row[4] 
       self.status = row[5] 
       self.publishID = row[6] 
       self.goardID = row[7] 
       self.LikesID = row[8] 
       self.createdDate = row[9] 
       self.createdTime = row[10] 
       self.hide = row[11] 
x = newThink() 
print x.create_New() 
print x.goalID, x.subscriptionID, x.LikesID, x.goardID 
see = x.addData('Just the Second', 'Nairobi', 89900845,'http://image.com/789900845') 
print see 

see = x.postData() 
print see 

see = x.getData(x.goalID) 
print see 


print "Now here is the formatted data../n" 
print '........' 
print x.description, x.Location, x.imageID, x.imageLink 

錯誤: 類型錯誤: '長' 對象有沒有屬性 '的GetItem'

這是我不斷收到錯誤。它返回一個元組,我猜想我不太確定

+0

哪條線引發異常? –

回答

0

你應該指出發生錯誤的位置。但我可以做一個猜測:

data = cursor.fetchone() 
.... 
for row in data: 
    self.ID = row[0] 
    ... 

data是一個元組,從一個row值。 for row in data迭代該元組,以便row將成爲單個字段。該錯誤表明其他row之一是一個數字,long

如果您使用data = cursor.fetchall(),那麼將會有多個rows數據,其餘的可能會工作。

或者堅持fetchone並跳過for row in data循環。只需使用data[0]等。

總之,請確保您瞭解data的結構。它可能不是你的代碼假設的元組的列表(或其他迭代)。