MySQL 与 Python 的连接器:按字段名称获取数据
MySQL connector with Python: getting data by field name
我必须从数据库中检索数据。现在我正在使用以下代码:
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']
谢谢
一种选择是使用 MySQLdb。然后你可以改变:
cursor = connection.cursor()
收件人:
cursor = connection.cursor(MySQLdb.cursors.DictCursor)
并通过字段名称而不是索引访问值。
根据 mysql-connector-python 文档,有两种方法可以实现此目的。
手动:
cursor = cnx.cursor()
cursor.execute(...)
row = dict(zip(cursor.column_names, cursor.fetchone()))
与 MySQLCursorDict
class:
cursor = cnx.cursor(dictionary=True)
我必须从数据库中检索数据。现在我正在使用以下代码:
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']
谢谢
一种选择是使用 MySQLdb。然后你可以改变:
cursor = connection.cursor()
收件人:
cursor = connection.cursor(MySQLdb.cursors.DictCursor)
并通过字段名称而不是索引访问值。
根据 mysql-connector-python 文档,有两种方法可以实现此目的。
手动:
cursor = cnx.cursor()
cursor.execute(...)
row = dict(zip(cursor.column_names, cursor.fetchone()))
与 MySQLCursorDict
class:
cursor = cnx.cursor(dictionary=True)