Home > Article > Backend Development > How do I pass parameters to a Pandas read_sql query?
When using Pandas to connect to a SQL database using an SQLAlchemy engine, there are multiple ways to pass parameters to an SQL query.
In particular, the read_sql method allows for passing parameters as either a list or tuple, as demonstrated in the example below:
<code class="python">df = psql.read_sql(('select "Timestamp","Value" from "MyTable" ' 'where "Timestamp" BETWEEN %s AND %s'), db,params=[datetime(2014,6,24,16,0),datetime(2014,6,24,17,0)], index_col=['Timestamp'])</code>
Alternatively, parameters can be passed as a dictionary, as seen in the documentation. However, the specific syntax you use for passing values in the SQL query depends on the database driver you are using.
In the case of psycopg2, the recommended syntax for named arguments is %(name)s, as demonstrated below:
<code class="python">df = psql.read_sql(('select "Timestamp","Value" from "MyTable" ' 'where "Timestamp" BETWEEN %(dstart)s AND %(dfinish)s'), db,params={"dstart":datetime(2014,6,24,16,0),"dfinish":datetime(2014,6,24,17,0)}, index_col=['Timestamp'])</code>
The above is the detailed content of How do I pass parameters to a Pandas read_sql query?. For more information, please follow other related articles on the PHP Chinese website!