Search code examples
pythonpython-3.xaws-lambdadynamic-sql

how to provide dynamic input for Sql statement in python


I am trying to execute a dynamic sql query in python. It looks like below.

import json
from decimal import Decimal
import psycopg2

def initial_execution(param_name):
    time = get_timestamp(param_name)
    query = 'SELECT name, account_mgr, addr1, addr2, ap_email, bill_to_nbr, billto_only, city, controlling_nbr, controlling_only, country, cust_contact, email, load_create_date, load_update_date, nbr, owner, sales_rep, source_system, state, station, zip FROM public.customers WHERE billto_only = 'Y' OR controlling_only = 'Y' AND load_create_date >= \''+time+'\' OR load_update_date >= \''+time+'\''
    queryData = execute_db_query(query)

execute_db_query -> this function runs in the redshift using pscopg2 I am executing this script by dynamically pulling the "time" from a user input. I am getting an error

[ERROR] Runtime.UserCodeSyntaxError: Syntax error in module
'src/customers': 
invalid syntax (customers.py, line 78) 
Traceback
(most recent call last):   File "/var/task/src/customers.py" 
Line 78 query = 'SELECT name,billto_only, controlling_only , load_create_date, load_update_date, nbr, owner, sales_rep,
 source_system, state, station, zip FROM public.test WHERE billto_only
 = 'Y' OR controlling_only = 'Y' AND load_create_date >= \''+time+'\' OR load_update_date >= \''+time+'\''

The same query in sql is written like below and executes correctly

SELECT name,billto_only,  controlling_only,load_create_date, load_update_date, nbr, owner, sales_rep, source_system, state, station, zip FROM public.test
WHERE (billto_only = 'Y' OR controlling_only = 'Y') AND (load_create_date >= '2020-10-09 07:04:51' OR load_update_date >= '2020-10-09 07:04:51') limit 5;

Solution

  • Could be off the mark, but the 'Y' will be breaking your string?

    query = 'SELECT name,billto_only, controlling_only , load_create_date, load_update_date, nbr, owner, sales_rep, source_system, state, station, zip FROM public.test WHERE billto_only = \'Y\' OR controlling_only = \'Y\' AND load_create_date >= \''+time+'\' OR load_update_date >= \''+time+'\''
    

    Escaped apostrophes