在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的创建者最终会为我们这样做吗?
发布于 2014-04-04 04:13:28
一个可能的解决方案是像这样对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连接器包中。
我测试过这个,它确实有效。
更新:如下所述卡尔·M.W.在v2 of mysql.connector中不再需要这个子类。mysql.connector已经更新,现在可以使用以下选项启用字典游标。
cursor = db.cursor(dictionary=True)
发布于 2014-12-15 19:55:21
此示例工作如下:
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
发布于 2017-09-18 17:56:49
使用Python3.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。
https://stackoverflow.com/questions/22769873
复制相似问题