Reputation: 11
I've created a valid connection through sqlalchemy when I didn't pass variables into my tape_query string, which is a multi-statement query. However, when I tried to pass sp_input through :sp into the string per below, I get a KeyError: 'data_date' error per below. What am I missing?
what works:
"""
USE DATABASE this;
USE SCHEMA that;
SELECT * from table where id=100;
"""
conn = engine.connect()
for q in tape_query.split(";"):
conn.execute(q)
what doesn't work:
tape_query=
"""
USE DATABASE this;
USE SCHEMA that;
SELECT * from table where id=:sp;
"""
sp_input=200
conn = engine.connect()
for q in tape_query.split(";"):
conn.execute(q, {"sp":sp_input})
the error looks like this:
~\anaconda3\lib\site-packages\snowflake\connector\cursor.py in execute(self, command, params, timeout, >_exec_async, _do_reset, _put_callback, _put_azure_callback, _put_callback_output_stream, _get_callback, >_get_azure_callback, _get_callback_output_stream, _show_progress_bar, _statement_params, _is_internal, >_no_results, _use_ijson, _is_put_get, _raise_put_get_error, _force_put_overwrite) 509 params, processed_params) 510 if len(processed_params) > 0: --> 511 query = command % processed_params 512 else: 513 query = command
KeyError: 'data_date'
Upvotes: 1
Views: 1829
Reputation: 1210
Perhaps you could try something like this? If not, then maybe dig into the documentation.
https://docs.sqlalchemy.org/en/13/core/engines.html
https://docs.sqlalchemy.org/en/13/core/connections.html
from sqlalchemy import create_engine
engine = create_engine('postgresql://scott:tiger@localhost:5432/mydatabase')
sp_input = [100, 200]
query_string = f"select * from table1 where id={sp_input[0]}; select * from table2 where id={sp_input[1]}"
connection = engine.raw_connection()
try:
cursor = connection.cursor()
cursor.execute(query_string)
results_one = cursor.fetchall()
cursor.nextset()
results_two = cursor.fetchall()
cursor.close()
finally:
connection.close()
Upvotes: 0