2

I am trying to parameterise a snowflake query in python but it doesn't work. Here is the code:

 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)

The error I get is " : must be real number, not str". I am not sure why I get this error.Is there a better way of passing variables in a query?

Beginner
  • 57
  • 2
  • 10

2 Answers2

1

Found a solution that works:

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})
Beginner
  • 57
  • 2
  • 10
0

Using the f-string is easiest I think.
Advantage is that this solution is database independent.

your_param = "Sander"

your_query = f"""
    select *
    from your_table
    where id = '{your_param}'  # if your id is numeric then don't use the single quotes!
"""

df = pd.read_sql(your_query, db_connection)

See also: Snowflake Python connector insert doesn't accept variables

Sander van den Oord
  • 10,986
  • 5
  • 51
  • 96