如何使用 pandas pd.read_sql_query 使用多个参数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40180884/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I use multiple parameters using pandas pd.read_sql_query?
提问by mattk
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.
我试图在 sql 查询中传递三个变量。它们是区域、功能、新用户。我正在使用 SQL 驱动程序 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: []
回答by Steven G
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))
回答by mattk
Operator error by me :( I was using the wrong variable and the database returned no results because it didn't exist!
我的操作员错误:(我使用了错误的变量,数据库没有返回任何结果,因为它不存在!