mysql中取别名能看到_MySQL:从查询中获取列名或别名

bd96500e110b49cbb3cd949968f18be7.png

I'm not asking for the SHOW COLUMNS command.

I want to create an application that works similarly to heidisql, where you can specify an SQL query and when executed, returns a result set with rows and columns representing your query result. The column names in the result set should match your selected columns as defined in your SQL query.

In my Python program (using MySQLdb) my query returns only the row and column results, but not the column names. In the following example the column names would be ext, totalsize, and filecount. The SQL would eventually be external from the program.

The only way I can figure to make this work, is to write my own SQL parser logic to extract the selected column names.

Is there an easy way to get the column names for the provided SQL?

Next I'll need to know how many columns does the query return?

# 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 will give you a tuple of tuples where [0] for each is the column header.

num_fields = len(cursor.description)

field_names = [i[0] for i in cursor.description]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值