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?
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})
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.