MySQL:从查询结果中检索列标题
问题:
我们如何检索使用 MySQLdb 在 Python 中获取 MySQL 查询结果集的列名或别名?要求是结果集中的列名应与 SQL 查询中指定的选定列匹配。
答案:
从使用MySQLdb查询MySQL结果集,步骤如下:
代码示例:
<code class="python"># Python import MySQLdb # Connect to MySQL db = MySQLdb.connect(host="myhost", user="myuser", passwd="mypass",db="mydb") # Execute the query sql = """ SELECT ext, SUM(size) AS totalsize, COUNT(*) AS filecount FROM fileindex GROUP BY ext ORDER BY totalsize DESC; """ cursor = db.cursor() cursor.execute(sql) # Get column names column_names = [i[0] for i in cursor.description] # Print results while (1): row = cursor.fetchone () if row == None: break print("%s %s %s\n" % (row[0], row[1], row[2])) # Get number of columns num_fields = len(cursor.description) # Close cursor and database connection cursor.close() db.close() print("Number of columns:", num_fields) print("Column names:", column_names)</code>
以上是如何使用 MySQLdb 从 Python 中的 MySQL 查询结果集中检索列名?的详细内容。更多信息请关注PHP中文网其他相关文章!