Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pandas read_sql return query string with arguments passed

Tags:

python

sql

pandas

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?

like image 516
natsuki_2002 Avatar asked Mar 18 '16 15:03

natsuki_2002


People also ask

What does read_sql_query return?

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.

How does PD Read_sql work?

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.

Can we use SQL query in pandas DataFrame?

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.

What is Pandasql?

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.


1 Answers

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']
like image 116
idubs11 Avatar answered Oct 24 '22 20:10

idubs11