python mysql.connector 字典游标?
在Python的mysqldb
中,我可以这样声明一个字典游标:
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的开发者最终会为我们实现这个功能吧?
5 个回答
我也遇到过同样的问题,就是默认的光标返回的元组没有列名。
解决办法在这里:
使用 MySQLdb.cursors.DictCursor 时出现错误
你可以在配置中加这一行:app.config["MYSQL_CURSORCLASS"] = "DictCursor"
我在使用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文件。
这个例子可以正常工作:
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
根据这篇文章,你可以通过在游标构造函数中传入 'dictionary=True' 来实现这个功能:http://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursordict.html
所以我试了试:
cnx = mysql.connector.connect(database='bananas')
cursor = cnx.cursor(dictionary=True)
结果是:TypeError: cursor() got an unexpected keyword argument 'dictionary'
然后我又试了:
cnx = mysql.connector.connect(database='bananas')
cursor = cnx.cursor(named_tuple=True)
结果是:TypeError: cursor() got an unexpected keyword argument 'named_tuple'
我也试了这个:cursor = MySQLCursorDict(cnx)
但是都没成功。显然我用的版本不对,我怀疑我们只需要耐心等一下,因为文档在http://downloads.mysql.com/docs/connector-python-relnotes-en.a4.pdf中提到这些新功能目前还处于测试阶段。
一个可能的解决办法是像下面这样对 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()
方法返回的是一个 字典
,而不是一个 元组
。
我在mysql论坛上发现了这个方法,我相信是mysql的开发者自己发布的。我希望他们有一天能把这个功能加入到mysql连接器包里。
我测试过这个方法,确实有效。
更新:正如Karl M.W.下面提到的,在mysql.connector的第2版中,这个子类已经不再需要了。mysql.connector已经更新,现在你可以使用以下选项来启用字典游标。
cursor = db.cursor(dictionary=True)