![](/img/trans.png)
[英]How to connect to Snowflake using python snowflake connector from within Databricks in Python 3?
[英]Getting column header from snowflake table using python snowflake connector
如何使用雪花连接器 cursor 获取表数据和列名。 好吧,我可以使用 dictcursor 获得它,但是合并结果集变得很复杂,因为它将所有数据作为密钥对。 我想知道是否有任何直接的方法。
要获取列标题,您可以使用光标的description
属性,该属性返回结果的元数据并在此处进行描述。
像下面这样使用它:
import snowflake.connector
import os
snowflake_username = os.environ['SNOWFLAKE_USERNAME']
snowflake_password = os.environ['SNOWFLAKE_PASSWORD']
snowflake_account = os.environ['SNOWFLAKE_ACCOUNT']
snowflake_warehouse = os.environ['SNOWFLAKE_WAREHOUSE']
snowflake_database = 'sample_data'
snowflake_schema = 'tpch_sf1'
if __name__ == '__main__':
with snowflake.connector.connect(
user=snowflake_username,
password=snowflake_password,
account=snowflake_account,
warehouse=snowflake_warehouse,
database=snowflake_database,
schema=snowflake_schema,
autocommit=False
) as con:
# Execute cursor and print metadata
cursor = con.cursor().execute("select * from sample_data.TPCH_SF1.customer limit 10")
for c in cursor.description:
print(c)
# # Fetch and print results
# results = cursor.fetchall()
# print(results)
上面打印出来:
('C_CUSTKEY', 0, None, None, 38, 0, False)
('C_NAME', 2, None, 25, None, None, False)
('C_ADDRESS', 2, None, 40, None, None, False)
('C_NATIONKEY', 0, None, None, 38, 0, False)
('C_PHONE', 2, None, 15, None, None, False)
('C_ACCTBAL', 0, None, None, 12, 2, False)
('C_MKTSEGMENT', 2, None, 10, None, None, True)
('C_COMMENT', 2, None, 117, None, None, True)
我有同样的问题,在 Jupyter 笔记本中使用 python 雪花连接器。 我使用数据框,因此根据上面@SimonD 的回答,我将cursor.description
部分改编为:
hdrs = pd.DataFrame(cursor.description)
df = pd.DataFrame(sql_data)
根据我的数据,生成的hdrs
dataframe 具有一个属性“名称”,我可以使用该属性为df
dataframe 设置列名称,如下所示:
df.columns = hdrs['name']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.