首页 > 解决方案 > 我可以在python中使用名称列吗?

问题描述

我希望能够在 python 中使用我的 SQL 表。我设法使用代码连接和访问我的表。

我想知道是否可以在我的代码中检索列名。

我已经有了我的列:

ACTION    |    MANAGER
123             XYZ
456             ABC
PersonnesQuery = "SELECT........"
cursor = mydb.cursor()
cursor.execute(PersonnesQuery)
records_Personnes = cursor.fetchall()


for row in records_Personnes:
   if (row["MANAGER"] == "XYZ"):
                ..................
   elif (row["MANAGER"] == "ABC"):
                ................    


引用的方式似乎不起作用。但是,它适用于数字,例如 row[0]。但我想按列名

标签: pythonsql

解决方案


我假设您使用的是 pymysql 库,在这种情况下,有一种称为DictCursor的特定游标。这会将结果作为字典而不是列表返回。

cursor = mydb.cursor(pymysql.cursors.DictCursor)
cursor.execute(PersonnesQuery)
records_Personnes = cursor.fetchall()

推荐阅读