[英]How to get column names from a SQL query?
I need to put data from the SQL query into a Pandas dataframe.我需要将来自 SQL 查询的数据放入 Pandas dataframe 中。 Please tell me is it possible to get column names the query results?请告诉我是否可以获取查询结果的列名? I found that there is a keys()
function in sqlalchemy for that but it does not work for me:我发现在 sqlalchemy 中有一个keys()
function ,但它对我不起作用:
import mysql.connector
import pandas as pd
mydb = mysql.connector.connect(
host="SQLServer",
user="sqlusr",
password="usrpasswd",
database="sqldb"
)
cursor = mydb.cursor()
Query="SELECT Title, Review, Rate FROM reviews;"
cursor.execute(Query)
df = pd.DataFrame(cursor.fetchall())
df.columns = cursor.keys()
AttributeError: 'CMySQLCursor' object has no attribute 'keys' AttributeError: 'CMySQLCursor' object 没有属性 'keys'
I think that it your are searching for我认为您正在寻找
cnx = mysql.connector.connect(user=DB_USER, password=DB_USER_PASSWORD, host=DB_HOST, database=DB_NAME)
cursor = cnx.cursor()
query = ("SELECT `name`, `ftp_name`, `created_at`, `status` AS `status_customer` FROM `customers"
"WHERE `status` = %(status)s")
cursor.execute(query, { 'status': 1 })
# 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]
print(num_fields)
print(field_names)
>>> 4
>>> [u'name', u'ftp_name', 'created_at', u'status_customer']
# OR just use this cursor function:
print(cursor.column_names)
>>> (u'name', u'ftp_name', 'created_at', u'status_customer')
Hope this helps!希望这可以帮助!
SHOW COLUMNS FROM your-database-name.your-table-name显示来自您的数据库名称的列。您的表名称
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.