2014-03-31 66 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模块。 –

相关问题