How do I pass parameters to a Pandas read_sql query?

Barbara Streisand
Release: 2024-10-30 14:28:02
Original
762 people have browsed it

How do I pass parameters to a Pandas read_sql query?

Pandas read_sql with Parameters

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template