如何从 SQL 查询中获取列名?
How to get column names from a SQL query?
我需要将 SQL 查询中的数据放入 Pandas 数据框中。请告诉我是否可以获取查询结果的列名?我发现在 sqlalchemy 中有一个 keys()
函数,但它对我不起作用:
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'
显示您的数据库中的列-name.your-table-名称
我认为你正在寻找
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')
希望对您有所帮助!
我需要将 SQL 查询中的数据放入 Pandas 数据框中。请告诉我是否可以获取查询结果的列名?我发现在 sqlalchemy 中有一个 keys()
函数,但它对我不起作用:
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'
显示您的数据库中的列-name.your-table-名称
我认为你正在寻找
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')
希望对您有所帮助!