2012-10-31 62 views
-1

我希望能夠做一些類似下面的代碼(這是PHP):蟒蛇獲得通過列名數組元素,比如在PHP

while($row = mysql_fetch_array($result)){ 
    $name = $row['name']; 
    $event = $row['event']; 
在python

。所以通過它的索引獲得一個元素。什麼是最好的方法?

+0

使用Python Dictionary,Python列表只能通過它們的索引訪問。 –

+1

你是專門討論SQL結果數組還是一般數組? – lucasg

+0

使用這樣的東西:http://stackoverflow.com/questions/811548/sqlite-and-python-return-a-dictionary-using-fetchone –

回答

3

是的,使用dictionaries,它們是內置的類型。

d = {'name': 'user'} 
print d['name'] 
user 
+0

這似乎很有用。你能告訴我如何在練習中爲每一行取得我的'姓名'變量嗎? – trainoasis

1

您使用MySQLdb軟件包中的DictCursor對象。這將在結果集中產生一個字典(映射),而不是通常的元組。

import MySQLdb                              
from MySQLdb import cursors 

def fetchallmap(self, q, *args):                         
    """Fetch all rows into a dictionary.                       
    """                               
    curs = self._connection.cursor(cursors.DictCursor)                     
    curs.execute(q, args)                          
    res = curs.fetchall()                          
    curs.close()                             
    self._connection.commit()                            
    return res 

這將返回一個字典列表(映射)。如果您只需要一行,只需替換fetchoone而不是fetchall

def fetchonemap(self, q, *args):                         
    """Fetch one row into a dictionary.                       
    """                               
    curs = self._connection.cursor(cursors.DictCursor)                     
    curs.execute(q, args)                          
    res = curs.fetchone()                          
    curs.close()                             
    self._connection.commit()                            
    return res                             
+0

你能告訴我這將如何在我的情況下實際工作嗎?我如何得到給定的每一行的'名稱'和其他變量? – trainoasis

+1

這裏是一個例子:[http://www.kitebird.com/articles/pydbapi.html#TOC_10](http://www.kitebird.com/articles/pydbapi.html#TOC_10) – lucasg

+0

發佈爲'answer'所以我可以接受它:)),工作!非常感謝 – trainoasis