How can I use multiple parameters using pandas pd.read_sql_query?

本小妞迷上赌 提交于 2020-05-11 10:21:06

问题


I am trying to pass three variables in a sql query. These are region, feature, newUser. I am using SQL driver SQL Server Native Client 11.0.

Here is my code that works.

query = "SELECT LicenseNo FROM License_Mgmt_Reporting.dbo.MATLAB_NNU_OPTIONS  WHERE Region = ?"

data_df = pd.read_sql_query((query),engine,params={region})

output.

     LicenseNo
 0           12
 1            5

Instead i want to pass in three variables and this code does not work.

query = "SELECT LicenseNo FROM License_Mgmt_Reporting.dbo.MATLAB_NNU_OPTIONS WHERE Region = ? and FeatureName = ? and NewUser =?"

nnu_data_df = pd.read_sql_query((query),engine,params={region, feature, newUser})

Output returns an empty data frame.

Empty DataFrame
Columns: [LicenseNo]
Index: []

回答1:


try a string in a tuple, also you can take out the () in the query:

so you could do something like

query = "SELECT LicenseNo FROM License_Mgmt_Reporting.dbo.MATLAB_NNU_OPTIONS WHERE Region = ? and FeatureName = ? and NewUser =?"
region = 'US'
feature = 'tall'
newUser = 'john'
data_df = pd.read_sql_query(query, engine, params=(region, feature , newUser))



回答2:


Operator error by me :( I was using the wrong variable and the database returned no results because it didn't exist!



来源:https://stackoverflow.com/questions/40180884/how-can-i-use-multiple-parameters-using-pandas-pd-read-sql-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!