我不是要求 SHOW COLUMNS
命令。
我想创建一个与 heidisql 工作方式类似的应用程序,您可以在其中指定 SQL 查询,并在执行时返回一个结果集,其中包含代表查询结果的行和列。结果集中的列名应与您在 SQL 查询中定义的所选列相匹配。
在我的 Python 程序中(使用 MySQLdb
)我的查询只返回行和列结果,而不是列名。在以下示例中,列名将是 ext
、totalsize
和 filecount
。 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]
关于python - MySQL:从查询中获取列名或别名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5010042/