如何使用雪花连接器游标获取表数据和列名。 好吧,我可以使用 dictcursor 获得它,但是合并结果集变得很复杂,因为它将所有数据作为密钥对。 我想知道是否有任何直接的方法。
答案 0 :(得分:0)
要获取列标题,您可以使用游标的 description
属性,该属性返回结果的元数据并在 here 中进行描述。
像下面这样使用它:
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)