使用临时列名而不是索引从MySQL/Python查询检索数据

使用临时列名而不是索引从MySQL/Python查询检索数据,python,mysql,mysql-connector-python,Python,Mysql,Mysql Connector Python,如何使用列名从MySQL查询中检索数据我只是按索引使用它。例如,这是我的示例代码: query = ('SELECT Column1 as name, Column2 as lastname, Column 3 as othername FROM ' 'table WHERE condition = 1 ORDER BY name ASC LIMIT 1') cursor.execute(query) # I'll get just 1 result results = cur

如何使用列名从MySQL查询中检索数据我只是按索引使用它。例如,这是我的示例代码:

query = ('SELECT Column1 as name, Column2 as lastname, Column 3 as othername FROM '
         'table WHERE condition = 1 ORDER BY name ASC LIMIT 1')
cursor.execute(query) # I'll get just 1 result
results = cursor.fetchall()

if not results:
  connection.close()
  ..
else:
  for row in results:
    var = row[0] # <- Here is the problem, I am using the index to retrieve 
                 # the result from query, I wanna to use 'var = row["name"]' instead
                 # but this throw me an error because row must be integer type
    ...

我希望你能帮助我。谢谢,祝您愉快。

嘿,为了使用“行[名称]”,您需要为查询创建一个字典。这可以通过使用光标来完成

cursor=connection.cursorpysql.cursors.DictCursor cursor.executequery


希望这有帮助:

哦,我会试试的。但是,是否有其他方法可以使用临时列名从该查询中检索数据?请尝试。