简体   繁体   中英

How to use pd.read_sql with params

I am having trouble with parameterized queries with SQL server when trying to use pd.read_sql.

If I run

query = 'SELECT * FROM positions'
pd.read_sql(query,engine)

Then I get a good result:

        position_id                  position_name
    0             0             ACCOUNTING MANAGER
    1             1                     HR MANAGER
    ...
    ...
    ...

But if I run

query = 'SELECT ?,? FROM position_names'
params = ['position_id','position_name']
pd.read_sql(query, engine, params=params)

Then I get:

0   position_id  position_name
1   position_id  position_name
2   position_id  position_name
3   position_id  position_name
...
...

What am I doing wrong? Thanks for your help!

I believe that instead of reading the column names in as a param , you need to read them in as a columns .

Docs: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_sql.html

Parameters:

columns : list, default: None

List of column names to select from SQL table (only used when reading a table).

Change the query to the table name and pass list of columns to extract:

    query = 'position_names'
    columns = ['position_id','position_name']
    pd.read_sql(query, engine, columns=columns)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM