python - MySQL:从查询中获取列名或别名

我不是要求 SHOW COLUMNS 命令。

我想创建一个与 heidisql 工作方式类似的应用程序,您可以在其中指定 SQL 查询,并在执行时返回一个结果集,其中包含代表查询结果的行和列。结果集中的列名应与您在 SQL 查询中定义的所选列相匹配。

在我的 Python 程序中(使用 MySQLdb)我的查询只返回行和列结果,而不是列名。在以下示例中,列名将是 exttotalsizefilecount。 SQL 最终将在程序之外。

我能想到的唯一方法是编写我自己的 SQL 解析器逻辑来提取选定的列名。

有没有一种简单的方法来获取所提供 SQL 的列名? 接下来我需要知道查询返回了多少列?

# Python

import MySQLdb

#===================================================================
# connect to mysql
#===================================================================

try:
    db = MySQLdb.connect(host="myhost", user="myuser", passwd="mypass",db="mydb")
except MySQLdb.Error, e:
    print "Error %d: %s" % (e.args[0], e.args[1])
    sys.exit (1)

#===================================================================
# query select from table
#===================================================================

cursor = db.cursor ()   

cursor.execute ("""\
     select ext,
        sum(size) as totalsize,
        count(*) as filecount
     from fileindex
    group by ext
    order by totalsize desc;
""")

while (1):
    row = cursor.fetchone ()
    if row == None:
        break
    print "%s %s %s\n" % (row[0], row[1], row[2])

cursor.close()
db.close()      

最佳答案

cursor.description 将为您提供一个元组元组,其中每个元组的 [0] 是列标题。

num_fields = len(cursor.description)
field_names = [i[0] for i in cursor.description]

https://stackoverflow.com/questions/5010042/

相关文章:

mysql - UNION 和 ORDER BY 的使用不正确?

mysql - 在 Rails 迁移 (MySQL) 中,您能否指定新列的位置?

mysql - 什么 MySQL 类型最适合 "price"列?

mysql - 错误 : select command denied to user '

mysql - 允许所有远程连接,MySQL

mysql - 如何将数据库从 Amazon RDS MySQL 实例导出到本地实例?

sql - ON子句中的MySQL未知列

sql - 你能在 SQL 中定义 "literal"表吗?

mysql - 用大量测试数据填充数据库表

java - 如何解决无法加载身份验证插件 'caching_sha2_password' 问题