pandas read_sql return query string with arguments passed

Viewed 5677
import pandas as pd
q = """
     select *
     from tbl 
     where metric = %(my_metric)s
     ;
     """
params = {'my_metric':'sales'}
pd.read_sql(q, mysql_conn, params=params)

Im using pandas read_sql function to safely pass arguments to my query string. I would like to return the final query string with the arguments replaced as well as the results. So for example, return the string:

select *
from tbl 
where metric = 'sales'
;

Any way to do this?

4 Answers

To extend and fix some issues in @tvashtar 's answer

actual_q = query_string
for param in q_params:
    actual_param = param.strip('%(').strip(')s')
    # 'param1'
    form_param = '%\({}\)s'.format(actual_param)
    # '%s\\(param1\\)s'
    value = str(params[actual_param]) if params[actual_param] else "\'\'"
    # '' if no value else the str of param1
    actual_q = re.sub(form_param, value, actual_q)
    print(actual_q)

After processing through the list of params, actual_q will have the value replaced query string

Related