2014-03-31 118 views
14

在Python mysqldb我可以聲明遊標作爲字典光標這樣的:python mysql.connector DictCursor?

cursor = db.cursor(MySQLdb.cursors.DictCursor) 

這將使我的名字像這樣的引用在cursor環列:

for row in cursor: # Using the cursor as iterator 
    city = row["city"] 
    state = row["state"] 

是否有可能使用此MySQL連接器創建字典遊標? http://dev.mysql.com/doc/connector-python/en/connector-python-example-cursor-select.html

他們的例子只返回一個元組。

我想MySQL的創建者最終會爲我們做這件事嗎?

+0

你有沒有得到一個很好的答案。如果不是的話,我即將把Python3和mySQL註銷,因爲還沒有準備好黃金時段。嚴重的是,F他們在Pythin 3的6年以後發佈了這個廢話。 – user949300

+0

請參閱下面的jpatokal的評論...您需要Python/Connector v2.0.0 +來獲取MySQLCursorDict。你可以用mysql.connector .__ version__檢查你的版本。 – panofish

+0

您應該爲Python使用mysql.connector。然後你可以使用這個例子:http://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursordict.html。我還在該鏈接末尾添加了一條用戶註釋,其中討論瞭如何使用存儲過程來實現這一點。 – Blairg23

回答

9

一種可能的解決方案涉及子類MySQLCursor類這樣的:

class MySQLCursorDict(mysql.connector.cursor.MySQLCursor): 
    def _row_to_python(self, rowdata, desc=None): 
     row = super(MySQLCursorDict, self)._row_to_python(rowdata, desc) 
     if row: 
      return dict(zip(self.column_names, row)) 
     return None 

db = mysql.connector.connect(user='root', database='test') 

cursor = db.cursor(cursor_class=MySQLCursorDict) 

現在_row_to_python()方法返回dictionary代替tuple

我在mysql論壇上發現了這個,我相信它是由mysql開發者自己發佈的。我希望他們有一天將它添加到mysql連接器包中。

我測試了這個,它確實有效。

更新:正如下面由Karl M.W所提到的...這個子類在mysql.connector的v2中不再需要。 mysql.connector已更新,現在可以使用以下選項啓用字典光標。

cursor = db.cursor(dictionary=True) 
+4

我一直習慣使用這種方法,但是從v2開始,您可以使用本地字典支持:cursor = db.cursor(dictionary = True) –

+0

是的,由於大多數發行版仍然使用v1.1,因此它仍然派上用場:/ – techouse

12

根據這篇文章在經過 '字典=真',將光標構造它是可用: http://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursordict.html

所以我嘗試:

cnx = mysql.connector.connect(database='bananas') 
cursor = cnx.cursor(dictionary=True) 

,並得到: 類型錯誤:cursor()得到了一個意想不到的關鍵字參數'dictionary'

,我嘗試:

cnx = mysql.connector.connect(database='bananas') 
cursor = cnx.cursor(named_tuple=True) 

,並得到: 類型錯誤:光標()得到了一個意想不到的關鍵字參數 'named_tuple'

,我嘗試這一個了:cursor = MySQLCursorDict(cnx)

但無濟於事。顯然,我在這裏的版本是錯誤的,我懷疑我們必須耐心等待,因爲文檔http://downloads.mysql.com/docs/connector-python-relnotes-en.a4.pdf表明這些新功能在寫作階段處於alpha階段。

+0

偉大的更新...我認爲這只是時間問題。 – panofish

+2

您需要Python/Connector v2.0.0 +來獲取MySQLCursorDict。你可以用'mysql.connector .__ version__'來檢查你的版本。 – jpatokal

+0

太棒了!我只是更新到V2,我的自定義MySQLCursorDict cursor_class通過生成列表而不是字典停止工作。這解決了我的問題。替換cursor_class = with dictionary = True在v2中有效。 –

7

這個例子的工作原理:

cnx = mysql.connector.connect(database='world') 
cursor = cnx.cursor(dictionary=True) 
cursor.execute("SELECT * FROM country WHERE Continent = 'Europe'") 

print("Countries in Europe:") 
for row in cursor: 
    print("* {Name}".format(Name=row['Name'] 

請記住,在這個例子中,'Name'是具體到被引用的數據庫列名。

另外,如果你想使用存儲過程,而是執行此操作:

cursor.callproc(stored_procedure_name, args) 
result = [] 
for recordset in cursor.stored_results(): 
    for row in recordset: 
     result.append(dict(zip(recordset.column_names,row))) 

其中stored_procedure_name是使用存儲過程的名稱和args是對於存儲過程的參數列表(離開這個如果沒有參數傳入,字段爲空,如[])。

這是從MySQL文檔的例子在這裏找到:http://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursordict.html

+2

謝謝!永遠讓我找到這個解決方案。對於callproc,遊標會忽略dictionary = True。 –

2

使用Python 3.6.2和MySQLdb的版本1.3.10,我得到這個一起工作:

import MySQLdb 
import MySQLdb.cursors 

... 

conn = MySQLdb.connect(host='...', 
         <connection info>, 
         cursorclass=MySQLdb.cursors.DictCursor) 

try: 
    with conn.cursor() as cursor: 
     query = '<SQL>' 
     data = cursor.fetchall() 
     for record in data: 
      ... record['<field name>'] ... 

finally: 
    conn.close() 

我使用PyCharm,並簡單地挖掘MySQLdb模塊connections.py和cursors.py。

+0

這是我工作的唯一答案,謝謝! – mishkin

+0

鑑於OP的問題,這應該是選擇的答案。 [MySQLdb](http://mysql-python.sourceforge.net/MySQLdb.html)和[mySQL連接器](https://dev.mysql.com/doc/connector-python/en/)是兩種不同的Python模塊。 –

相關問題