mysql连接器与python:按字段名获取数据

643ylb08  于 2021-06-20  发布在  Mysql
关注(0)|答案(2)|浏览(322)

我必须从数据库中检索数据。现在我使用以下代码:

import mysql.connector

connection = mysql.connector.connect(user, password, host, database)

cursor = connection.cursor()
cursor.execute(*Query*)
data = cursor.fetchall()
name = data[0][0]
surname = data[0][1]

我需要通过字段名而不是原始索引来访问数据。举个例子

name = data[0]['name']
surname = data[0]['surname']

谢谢

uoifb46i

uoifb46i1#

一种选择是使用mysqldb。然后您可以更改:

cursor = connection.cursor()

收件人:

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

并通过字段名而不是索引访问值。

0g0grzrc

0g0grzrc2#

根据mysql连接器python文档,有两种方法可以实现这一点。
手动:

cursor = cnx.cursor()
cursor.execute(...)
row = dict(zip(cursor.column_names, cursor.fetchone()))

MySQLCursorDict 班级:

cursor = cnx.cursor(dictionary=True)

相关问题