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?
Read SQL query into a DataFrame. Returns a DataFrame corresponding to the result set of the query string. Optionally provide an index_col parameter to use one of the columns as the index, otherwise default integer index will be used.
pandas read_sql() function is used to read SQL query or database table into DataFrame. This is a wrapper on read_sql_query() and read_sql_table() functions, based on the input it calls these function internally and returns SQL table as a two-dimensional data structure with labeled axes.
Pandasql is a python library that allows manipulation of a Pandas Dataframe using SQL. Under the hood, Pandasql creates an SQLite table from the Pandas Dataframe of interest and allow users to query from the SQLite table using SQL.
pandasql allows you to query pandas DataFrames using SQL syntax. It works similarly to sqldf in R. pandasql seeks to provide a more familiar way of manipulating and cleaning data for people new to Python or pandas.
OK, in that case try this:
import pandas as pd
q = """
select *
from tbl
where metric = %s
;
"""
params = {'my_metric': 'sales'}
df = pd.read_sql(q, mysql_conn, params=[params['my_metric']])
query_string = q % params['my_metric']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With