首页 > 解决方案 > 使用雪花连接器和熊猫在查询中传递变量

问题描述

我正在尝试在 python 中参数化雪花查询,但它不起作用。这是代码:

 ctx = snowflake.connector.connect(user=user, password=password, account=xxx)
    cs = ctx.cursor()
    cs.execute("use role {};".format(SNOWFLAKE_ROLE))
    cs.execute("use warehouse {}; ".format(SNOWFLAKE_WAREHOUSE))
    cs.execute("use database {};".format(database))
    cs.execute("use schema {};".format(schema))
    cs.execute("alter warehouse {} resume if suspended;".format(SNOWFLAKE_WAREHOUSE))
    
    id=500000
    
    query="""
    create or replace temp table test  as 
    select *
    from tablename as a
    where acct_id =%id;
    """
    
    df1 = pandas.read_sql_query(query, ctx,params={id})
    print(df1)

我得到的错误是“:必须是实数,而不是 str”。我不确定为什么会出现此错误。是否有更好的方法在查询中传递变量?

标签: pythonsqlpandassnowflake-cloud-data-platform

解决方案


找到了一个可行的解决方案:

query="""
    create or replace temp table test  as 
    select *
    from tablename as a
    where acct_id ={id};
    """
df1 = pandas.read_sql_query(query, ctx,params={'acct_id':id})

推荐阅读